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
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With