C#WinForms:使用来自两个不同表的数据源填充datagridview

时间:2015-07-17 01:17:53

标签: c# winforms linq datagridview

当我必须用一个表填充dgv时,没关系,我知道怎么做(List< Entity>来自数据库到数据源)。但是当我有一个FK与另一个表的表时,我不知道如何显示该表的另一个属性(而不是用户不会理解的ID)。我认为我对LINQ的所作所为非常糟糕(顺便说一下,我是LINQ的新手,我不知道我是否需要它,至少在这里)。当我尝试从DGV获取所选ID时,我的解决方案出现问题。

private void LoadDGV()
    {
        BuildingLogic oBuildingLogic;
        try
        {
            oBuildingLogic = new BuildingLogic();
            SocietyLogic oSocietyLogic = new SocietyLogic();
            List<Building> listBuildings = oBuildingLogic.GetAll();
            List<Society> listSocieties = oSocietyLogic.GetAll();


            this.dgvBuildings.DataSource = (from building in listBuildings
                                            join society in listSocieties
                                            on building.IDSociety equals society.ID
                                            select new { building.ID, FullName = building.FullName, ShortName = building.ShortName, Society = society.Name, Date = building.Date, City = building.City, Address = building.Adress }).ToList();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            oBuildingLogic = null;
        }
    }

    private int ItemSelectedID()
    {
        if (this.dgvBuildings.SelectedRows.Count > 0)
        {
            //something like this?
            //this.dgvBuildings.SelectedRows[0].DataBoundItem;
        }
        else
        {
            return 0;
        }
    }

1 个答案:

答案 0 :(得分:0)

return Convert.ToInt32(this.dgvBuildings.SelectedRows[0].Cells[0].Value);