Adam Bretz

I've got a bunch of DataGridViewComboBoxColumns in a DataGridView. I want to manually set the currently selected value. The ComboBox is populated from a list supplied from the database. The value I want to manually set is a member of the list from the database. I've tried doing it this way

Code Snippet
SetupGrid.Rows(0).Cells(
"ColumnName").Value = "SomeValueFromDBase"

I set up SetupGrid.Rows(0).Cells("ColumnName").Value as a watch value in the debugger, and it is correctly being set, it's just not displaying it properly. All of the DataGridViewComboBoxColumns are coded by hand and their datasource has been set to a datatable returned from a database.

Thank you for the help.



Re: Windows Forms Data Controls and Databinding Setting the value of a DataGridViewComboBoxColumn

Rong-Chun Zhang - MSFT

Hi Bretz,

When did you set the value for the cell I tested it, it worked well on my machine. If you want to set the value for the combox cell when the cell begins editing, we can handle the DataGridView.EditingControlShowing and set the select value to the ComboBox which is hosted in the cell. See my sample below:

Code Snippet

namespace NewDGV

{

public partial class DGVComboCellDefaultValue : Form

{

public DGVComboCellDefaultValue()

{

InitializeComponent();

}

private DataTable Cdt = new DataTable();

private DataTable Pdt = new DataTable();

private void DGVComboCellDefaultValue_Load(object sender, EventArgs e)

{

Cdt.Columns.Add("Id");

Cdt.Columns.Add("Name");

Cdt.Columns.Add("DescrId");

Cdt.Rows.Add("001", "aaa", "1");

Cdt.Rows.Add("002", "bbb", "2");

Cdt.Rows.Add("003", "ccc", "3");

Cdt.Rows.Add("004", "ddd", "1");

Pdt.Columns.Add("DescrId");

Pdt.Columns.Add("DescrName");

Pdt.Rows.Add("1", "Just a");

Pdt.Rows.Add("2", "Just b");

Pdt.Rows.Add("3", "Just c");

this.dataGridView1.DataSource = Cdt;

//this.dataGridView1.Columns.RemoveAt(2);

DataGridViewComboBoxColumn cbm = new DataGridViewComboBoxColumn();

cbm.HeaderText = "Descr";

cbm.DataPropertyName = "DescrId";

cbm.DisplayMember = "DescrName";

cbm.ValueMember = "DescrId";

cbm.DataSource = Pdt;

this.dataGridView1.Columns.Add(cbm);

this.dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);

}

void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

{

if (e.Control is ComboBox)

{

//set the SelectValue for the ComboBox hosted in the cell.

((ComboBox)e.Control).SelectedValue = "2";

}

}

private void button1_Click(object sender, EventArgs e)

{

//I use this line to test, it works well.

this.dataGridView1[3, 2].Value = "2";

}

}

}

Hope this helps.

Best Regards.