BindingSource与DataGridView组合框

Rod*_*Rod 4 c# winforms

我知道你可以使用BindingSourceDataGridView对象.

是否有可能在其中一个列中有一个组合框,仍然可以利用BindingSource

Jar*_*ley 8

是的,它是 - 在C#中查看带有DataGridView的ComboBox:

将ComboBox与DataGridView一起使用并不复杂,但在进行一些数据驱动的软件开发时几乎是必须的.

在此输入图像描述

我已经像这样创建了一个DataGridView.现在,我想在DataGridView中显示"Month"和"Item"而不是"MonthID"和"ItemID".

基本上就是本文介绍的是一个单独的绑定源绑定的组合框-在这种情况下,验证表,其中MonthIDMonthName存储,并根据从原始数据的ID显示月份名称.

在这里,他设置Month数据源,从月份表中选择,然后BindingSource从返回的数据中创建a .

//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;
Run Code Online (Sandbox Code Playgroud)

接着,他添加了一个月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);
Run Code Online (Sandbox Code Playgroud)

最后,他将DataGridView原始数据绑定.