我知道您可以将BindingSource
对象与DataGridView一起使用。
是否可以在其中一列中包含一个组合框并仍然可以利用BindingSource
?
答案 0 :(得分:8)
是的,它是 - 看看ComboBox with DataGridView in C#:
将ComboBox与DataGridView一起使用并不复杂,但在进行一些数据驱动的软件开发时几乎是必须的。
![]()
我已经像这样创建了一个DataGridView。现在,我想在DataGridView中显示“Month”和“Item”而不是“MonthID”和“ItemID”。
本文所描述的基本上是将组合框与单独的绑定源绑定 - 在本例中为验证表,其中存储了MonthID
和MonthName
,并且基于来自原始数据的ID。
在这里,他设置Month数据源,从月份表中选择,然后从返回的数据中创建BindingSource
。
//Month Data Source
string selectQueryStringMonth = "SELECT MonthID,MonthText FROM Table_Month";
SqlDataAdapter sqlDataAdapterMonth = new SqlDataAdapter(selectQueryStringMonth, sqlConnection);
SqlCommandBuilder sqlCommandBuilderMonth = new SqlCommandBuilder(sqlDataAdapterMonth);
DataTable dataTableMonth= new DataTable();
sqlDataAdapterMonth.Fill(dataTableMonth);
BindingSource bindingSourceMonth = new BindingSource();
bindingSourceMonth.DataSource = dataTableMonth;
然后他将月份ComboBoxColumn添加到DataGridView,使用DataSource
作为上面创建的BindingSource
:
//Adding Month Combo
DataGridViewComboBoxColumn ColumnMonth = new DataGridViewComboBoxColumn();
ColumnMonth.DataPropertyName = "MonthID";
ColumnMonth.HeaderText = "Month";
ColumnMonth.Width = 120;
ColumnMonth.DataSource = bindingSourceMonth;
ColumnMonth.ValueMember = "MonthID";
ColumnMonth.DisplayMember = "MonthText";
dataGridViewComboTrial.Columns.Add(ColumnMonth);
最后,他将DataGridView
绑定到原始数据。