BindingSource与DataGridViewcombobox

我知道你可以将BindingSource对象与DataGridView一起使用。

是否可以在其中一列中使用combobox并仍然可以利用BindingSource

是的,它是 – 用C#中的DataGridView查看ComboBox :

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

在此处输入图像描述

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

本文所描述的基本上是将combobox与单独的绑定源绑定 – 在本例中是一个validation表,其中存储了MonthIDMonthName ,并且根据原始数据中的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到原始数据。