I am attempting to populate a DataGridViewComboBoxColumn with a list of strings then select one of them based upon their value on form load.
A simple task one would think, but I just can't get it right.
I am populating a DataGridViewComboBoxColumn with strings as such without a problem:
ComboBoxColumn.Items.AddRange("Mr.", "Ms.", "Mrs.", "Dr.");
I also seem to be able to add it to the DataGridView without a problem (This is incorrect see Edit):
ExampleDataGrid.Rows.Add("", ComboBoxColumn, 1000, "");
Now I want to set "Mr." to be selected on load. Other posts suggest that I should be able to simply use:
ExampleDataGrid.Rows[i].Cells["ExampleColumnName"].Value = "Mr.";
But whenever I use it, I get an error that tells me the value is not valid. Is there something I'm missing?
I can however use this to get the set value without issue:
string Title = ExampleDataGrid.Rows[i].Cells["ExampleColumnName"].Value;
I had a look at the documentation but it doesn't seem to mention how to actually use .Value in this context. Microsoft Docs
Any thoughts on where I am going wrong would be great.
Edit:
The issue I was having was caused by me setting the ComboBoxItems in the "ExampleDataGrid.Rows.Add()". This should actually contain the value you want to set. e.g.
ExampleDataGrid.Rows.Add("", "Mr.", 1000, "");
You can initialize the DataGridView
this way:
private void Form1_Load(object sender, EventArgs e)
{
var textBoxColumn = new DataGridViewTextBoxColumn();
textBoxColumn.Name = "textBoxColumn";
var comboBoxColumn = new DataGridViewComboBoxColumn();
comboBoxColumn.Items.AddRange("A", "B", "C");
comboBoxColumn.Name = "comboBoxColumn";
dataGridView1.Columns.Add(textBoxColumn);
dataGridView1.Columns.Add(comboBoxColumn);
dataGridView1.Rows.Add("1", "A");
dataGridView1.Rows.Add("2", "B");
}
And then update the value of the comboBoxColumn
for the second row this way:
private void button1_Click(object sender, EventArgs e)
{
//You can use either of the following ways:
dataGridView1[1, 1].Value = "C";
//dataGridView1["comboBoxColumn", 1].Value = "C";
//dataGridView1.Rows[1].Cells["comboBoxColumn"].Value = "C";
//dataGridView1.Rows[1].Cells[1].Value = "C";
}
The value which you set for the cell, should be between the values which you added to Items
of the DataGridViewComboBoxColumn
.