Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...