DataGridView's Column name not found
Asked Answered
E

2

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();       
}
Eisen answered 20/2, 2014 at 16:22 Comment(3)
Do you see the column name or the column header displayed in the UIJeffry
yes, I do see MyEntity string displayed in the column headerEisen
See @h4xpace's answer - I believe you are using the header text and not the column name to refer to the columnJeffry
U
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.

Underpart answered 20/2, 2014 at 16:31 Comment(2)
Thank you so much. You saved the day. Great answer.Eisen
Incase it is not completely obvious, programmatically adding a checkbox with the name set should look like below: codeDataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn(); col.Width = 90; col.HeaderText = "Sync To Vend?"; col.Name = "Sync To Vend?"; ProductGrid.Columns.Insert(2, col); codeAndra
A
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;
        }
Andra answered 14/12, 2016 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.