Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BindingSource with DataGridView Combo Box

Tags:

c#

winforms

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?

like image 411
Rod Avatar asked Feb 19 '23 05:02

Rod


1 Answers

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.

like image 148
Jared Harley Avatar answered Feb 21 '23 02:02

Jared Harley