2012-06-26 89 views
0

數據我有2個表:的DataGridView +組合框+從2個表

第一:

id | 2ndTableId | Name 

二:

id | name 

我希望他們在的dataGridView顯示爲列: 1 - >組合框與第二表中的名稱列表(帶有一些where子句),選定的值=從第一個表'2ndTableId' 2->名稱從第一個表

此外我想保留在ComboBox 2值(id和名稱)。我使用Id和Name屬性創建了自己的MyComboBox類,但出現錯誤:

System.argumentException:DataGridViewComboBoxCell值無效。

我不知道如何管理這個。你可以幫我嗎?

回答

0

我有一個相同的場景。我爲兩個表創建了兩個DTO類並分配它們。 創建兩個類

public class Table1 
{ 
    public int Id { get; set; } 
    public int Table2Id { get; set; } 
    public string Name { get; set; } 
} 

public class Table2 
{ 
    public int Table2Id { get; set; } 
    public string Table2Name { get; set; } 
} 

然後在你創建一個DataGridView與四列。

Column1=> Name:idDropDown Default Text Style:DataGridViewCellStyle { } 
Column 2=> Name:Table1Id DataPropertyName:Table1Id 
Column 3=> Name:Table2Id DataPropertyName:Table2Id 
Column 4=> Name:Tbale1Name DataPropertyName:Tbale1Name 

然後用你需要的數據生成兩個列表。

List<Table1> dropDownList; 
List<Table2> gridData; 

在你的代碼使用方法如下

idDropDown.DisplayMember="Table2Name"; 
idDropDown.ValueMember="Table2Id"; 
idDropDown.DataSource=dropDownList; 

gridview1.AutoGenerateColumns = false; 
gridview1.DataSource=gridData; 

最主要的是我們要設置的AutoGenerateColumns爲False在此代碼