简体   繁体   English

找不到DataGridView的列名

[英]DataGridView's Column name not found

Why do I get the exception that Column Name is not found for MyEntity as well as FullName Columns? 为什么我没有找到MyEntity和FullName列的列名称的异常? Although I see the column names being displayed in UI. 虽然我看到列名在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();       
}

Because, infuriatingly enough, that datagridview column is not actually named the same as your DataTable column name. 因为,令人愤慨的是,datagridview列实际上并没有与DataTable列名相同。 If you look at the column collection in the designer Properties window, you will see that is probably named something like "DataGridViewColumn4" or similar. 如果查看设计器“属性”窗口中的列集合,您将看到它可能被命名为“DataGridViewColumn4”或类似名称。

If you know the index, you should use that, or rename the columns to the DT column names. 如果您知道索引,则应使用该索引,或将列重命名为DT列名称。

Incase it is not completely obvious, programmatically adding a checkbox to your datagridview with the name set should look like below: 包含它并不是很明显,以编程方式向您的datagridview添加一个名称为set的复选框应如下所示:

        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;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM