2014-03-04 37 views
1

我有一个DataGridView绑定到DataTable,我使用SQLiteDataAdapter更新一个SQLite数据库。我试图让其中一列成为DataGridViewComboBoxColumn,但尽管我可以在其上放置项目并更改其单元格值,但我无法通过DataAdapter更新它。将DataGridViewColumn更改为绑定DataGridView中的DataGridViewComboBoxColumn

一旦在DataGridView加载我这样做:

DataGridViewComboBoxColumn cbCol = new DataGridViewComboBoxColumn(); 
dataGridView1.Columns.Insert(2, cbCol); 
dataGridView1.Columns[2].HeaderText = dataGridView1.Columns[3].HeaderText; 
dataGridView1.Columns[3].Visible = false; 

string[] cbList = new[] {"item1","item2"}; 

foreach (string str in cbList) 
{ 
    cbCol.Items.Add(str); 
} 

for (int i = 0 ; i<= dataGridView1.Rows.Count - 1; i++) 
{ 
    dataGridView1.Rows[i].Cells[2].Value = dataGridView1.Rows[i].Cells[3].Value; 
} 

的问题是,ComboBoxColumn未绑定到DataTable,我要检查的变化和运行的DataAdapter之前修改隐藏列.Update。

有什么办法可以避免这种情况?完美的情况是这样的:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e) 
    { 
     if (columnadded.headertext == "xxx") 
     { 
      //Then this is column is the same but in a ComboBox format. 
      //The ComboBoxColumn, when added, must show the same values and have 
      //the same binding as if if was the regular column. 
     } 
    } 

回答

3

创建DataGridViewComboBoxColum,将其添加到网格和数据绑定。如果将列的DataPropertyName属性设置为数据库列ID,那么当数据绑定时,该数据列将绑定到网格列。 DataGridView将自动生成其他列(如果您设置了AutoGenerateColumns=true)。将第二个数据源绑定到组合框本身。

DataGridViewComboBoxColumn col1 = new DataGridViewComboBoxColumn(); 
col1.Name = //name of the column 
col1.HeaderText = //header text of the column 
col1.DataPropertyName = //db column id 
col1.DataSource = // datasource for combo 
dataGridView1.Columns.Add(col1); 

dataGridView1.AutoGenerateColumns = true; 
dataGridView1.DataSource = // your datasource 
+0

谢谢你,那就是我所需要的。我错过了DataPropertyName! –

0

我刚刚现在类似的问题,我不得不

col1.DisplayMember = "number"; //column name in source table for col1 

加入到上述溶液中,然后它的工作。

相关问题