Dusk
Dusk

Reputation: 2201

Combo box is not displaying default value in DataGridView in C#

I'm trying to allow user to select value from DataGridViewComboBoxColumn for each new row. I've bound ComboBox in GridView to database, but whenever I enter new row I see DataGridViewComboBoxColumn with no initial value. I have to set the value first.

How can I let default value appear in DataGridViewComboBoxColumn whenever I enter new row in DataGridView?

This is how I'm binding DataGridView ComboBox to database :

bindingSource1.DataSource = itemBAL.GetTable();
dataGridView1.DataSource = bindingSource1; 
ItemName.DataSource = bindingSource1; //Where ItemName is an instance ofDataGridViewComboBoxColumn
ItemName.DisplayMember = "Name";
ItemName.ValueMember = "ItemId";

Upvotes: 3

Views: 16715

Answers (3)

Donatas K.
Donatas K.

Reputation: 866

You can add Items to your DataGridViewComboBoxColumn in designer or in code.

Upvotes: 0

ilankes
ilankes

Reputation: 21

bindingSource1.DataSource = itemBAL.GetTable();
dataGridView1.DataSource = bindingSource1; 
ItemName.DataSource = bindingSource1; //Where ItemName is an instance ofDataGridViewComboBoxColumn
ItemName.DisplayMember = "Name";
ItemName.ValueMember = "ItemId";

add this line only

dataGridView1["ItemName",dataGridRowNumber].value=1;//item id value

Upvotes: 2

David Hall
David Hall

Reputation: 33143

You can use the DefaultCellStyle.NullValue and DefaultCellStyle.DataSourceNullValue properties of the combo box column.

There is a quite comprehensive MSDN article on this here.

I've also given a code example below:

// Let's say I have this list of cars I want to add to my datagridview
List<Car> cars = new List<Car>();
cars.Add(new Car() { Index = 0, Make = "Ford" });
cars.Add(new Car() { Index = 1, Make = "Chevvy" });
cars.Add(new Car() { Index = 2, Make = "Toyota" });

// I create the column, setting all the various properties
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataSource = cars;
col.Name = "Cars";
col.DisplayMember = "Make";
col.HeaderText = "Car";
col.ValueMember = "Index";
col.DataPropertyName = "Car";

// As well as standard properties for a combobox column I set these two:
col.DefaultCellStyle.NullValue = cars[0].Make;
col.DefaultCellStyle.DataSourceNullValue = cars[0].Index;

dataGridView1.Columns.Add(col);

dataGridView1.DataSource = dt;

One thing to note with the code above is that I am setting the DataPropertyName to allow binding with a property on the datagridview's datasource.

If I was not doing that then I would need to add some additional logic when accessing the combo box column when users have selected nothing, since the Value of the property would be null (the NullValue does not set a value to the actual cell, only shows a default value).

Upvotes: 7

Related Questions