6

Why do I get the exception that Column Name is not found for MyEntity as well as FullName Columns? Although I see the column names being displayed in UI.

InitializeComponent();

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    int rowIndex = dataGridView1.Rows.IndexOf(row);
    myObject = dataGridView1.Rows[rowIndex].Cells["MyEntity"].Value as IEntityObject;
    fileName = dataGridView1.Rows[rowIndex].Cells["FullName"].Value.ToString();       
}
davmos
  • 9,324
  • 4
  • 40
  • 43
user1298925
  • 2,304
  • 7
  • 29
  • 43

2 Answers2

15

Because, infuriatingly enough, that datagridview column is not actually named the same as your DataTable column name. If you look at the column collection in the designer Properties window, you will see that is probably named something like "DataGridViewColumn4" or similar.

If you know the index, you should use that, or rename the columns to the DT column names.

Serialize
  • 491
  • 5
  • 13
  • Thank you so much. You saved the day. Great answer. – user1298925 Feb 20 '14 at 16:38
  • Incase it is not completely obvious, programmatically adding a checkbox with the name set should look like below: `code`DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn(); col.Width = 90; col.HeaderText = "Sync To Vend?"; col.Name = "Sync To Vend?"; ProductGrid.Columns.Insert(2, col); `code` – Pearce Dec 14 '16 at 13:56
1

Incase it is not completely obvious, programmatically adding a checkbox to your datagridview with the name set should look like below:

        DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
        col.Width = 90;
        col.HeaderText = "Sync To Vend?"; //Header cell text
        col.Name = "SyncVendBox"; //This is the important part
        ProductGrid.Columns.Insert(2, col);

And if you want the checkbox ticked:

        for (int i = 0; i < ProductGrid.Rows.Count; i++)
        {
            ProductGrid.Rows[i].Cells["SyncVendBox"].Value = true;
        }
Pearce
  • 320
  • 4
  • 10