2

I have three columns , textbox, combobox and textbox in that order:

this.columnLocalName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnLocalAddress = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.columnLocalPort = new System.Windows.Forms.DataGridViewTextBoxColumn();   

And they are in turn in a datagridview like so:

this.dataGridViewLocalProfile.Columns.AddRange(
new System.Windows.Forms.DataGridViewColumn[] {
                    this.columnLocalName,
                    this.columnLocalAddress,
                    this.columnLocalPort});

Later on I will try to add different values to each combobox cell like so:

foreach (profile in localProfile.List)
{
DataGridViewComboBoxCell cell =(DataGridViewComboBoxCell)
(dataGridViewLocalProfile.Rows[dataGridViewLocalProfile.Rows.Count - 1].
Cells["columnLocalAddress"]);

cell.Items.Clear();
cell.Items.Add(profile.Address.ToString());

dataGridViewLocalProfile.Rows.Add(
new string[] { profile.Name, profile.Address, profile.Port });
}

This results in a datagrid with the first column and last column populated and the comboboxcolumn empty. with an dataerror which I handle. The message is:

DataGridViewComboBoxCell value is not valid.

I have read through most of the post, but can not find a solution to this.

I have tried with setting the datasource like so:

cell.DataSource = new string[] { profile.Address };

still getting empty comboboxcolumn with an dataerror saying

DataGridViewComboBoxCell value is not valid.

I think this is extra tricky since I add different values for each comboboxcell.

Can anyone, please help me as to how i can make this work.

/Best

User123456
  • 671
  • 2
  • 9
  • 19

1 Answers1

0

Late to the game, but here's the solution anyways.

The problem is in the foreach loop. The ComboBox cell from the last existing row is populated with an item. But then, a whole new row is added using the current profile object:

dataGridViewLocalProfile.Rows.Add( new string[] { profile.Name, profile.Address, profile.Port });

The items for the ComboBox cell in this new row is empty, therefore profile.Address is not valid. Change the foreach loop to look like this and you're gold:

foreach (Profile p in this.localProfile)
{
  DataGridViewRow row = new DataGridViewRow();
  row.CreateCells(this.dataGridView1);

  DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)row.Cells[1];
  cell.Items.Clear();
  cell.Items.Add(p.Address);

  row.Cells[0].Value = p.Name;
  row.Cells[1].Value = p.Address;
  row.Cells[2].Value = p.Port;
  this.dataGridView1.Rows.Add(row);
}
OhBeWise
  • 5,350
  • 3
  • 32
  • 60