Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

c# - BindingSource with DataGridView Combo Box

I know you can use the BindingSource object with a DataGridView.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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

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

//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 DataSource as the BindingSource created above:

//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 DataGridView to the original data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...