将DataGridViewColumn更改为绑定DataGridView中的DataGridViewComboBoxColumn

时间:2014-03-04 22:30:06

标签: c# winforms datagridview dataadapter datagridviewcombobox

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

一旦加载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.
       }
    }

2 个答案:

答案 0 :(得分:3)

创建DataGridViewComboBoxColum,将其添加到网格并绑定数据。如果将列的DataPropertyName属性设置为db列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

答案 1 :(得分:0)

我刚才有类似的问题,我不得不添加

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

以上解决方案,然后就可以了。