C# BindingSource 与 DataGridView 组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13829621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:55:03  来源:igfitidea点击:

BindingSource with DataGridView Combo Box

c#winforms

提问by Rod

I know you can use the BindingSourceobject with a DataGridView.

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

Is it possible to have a combo box in one of the columns and still take advantage of the BindingSource?

是否可以在其中一列中使用组合框并仍然利用BindingSource?

采纳答案by Jared Harley

Yes, it is - take a look at ComboBox with DataGridView in C#:

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

Using ComboBox with DataGridView is not that complex anymore but it's almost mandatory while doing some data driven software development.

enter image description here

I have created a DataGridView like this one. Now, I want to show “Month” and “Item” instead of “MonthID” and “ItemID” in DataGridView.

将 ComboBox 与 DataGridView 一起使用不再那么复杂,但在进行一些数据驱动的软件开发时几乎是强制性的。

在此处输入图片说明

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

Essentially what the article describes is binding the comboboxes with a separate binding source - in this case, a validation table, where MonthIDand MonthNameare stored, and the month name is displayed based on the id from the original data.

基本上,文章描述的是将组合框与单独的绑定源绑定 - 在这种情况下,是一个验证表,存储位置MonthIDMonthName存储位置,并根据原始数据中的 id 显示月份名称。

Here he sets up the Month data source, selecting from a month table, and then creates a BindingSourcefrom the returned data.

在这里,他设置了 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;

Then he adds the month ComboBoxColumn to the DataGridView, using the DataSourceas the BindingSourcecreated above:

接着,他添加了一个月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);

And then finally, he binds the DataGridViewto the original data.

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