如何通过其HeaderText属性获取DataGridViewColumn?

时间:2018-08-01 18:04:31

标签: c# datagridview datagridviewcolumn headertext

如何通过标题文本而不是通过index或name属性获得数据网格视图的列?

到目前为止,我尝试的是我的直观方法:

// Identifiers used are:
string myHeaderText = "Header Text";

dataGridViewColumn = dataGridView.Columns[myHeaderText];

无论如何返回

Object reference not set to an instance of an object.

1 个答案:

答案 0 :(得分:-1)

正在返回

Object reference not set to an instance of an object.

因为

dataGridViewColumn = dataGridView.Columns[myHeaderText];

在dataGridView中寻找具有 Name 属性= myHeaderText而不是 HeaderText 属性的列。要解决此问题,您可以尝试以下操作:

namespace Extensions
{
    // Class for: DataGridView Extensions
    public static class DataGridViewExtension
    {
        // Method for: Getting the DataGridViewColumn by the header text
        public static DataGridViewColumn IndexByHeaderText(this DataGridView dataGridView, 
            string headerText)
        {
            // Identifiers used are:
            DataGridViewColumn dataGridViewColumn = new DataGridViewColumn();
            int columnIndex;

            // Get the index (using LinearSearch, at worst O(n), could sort for better)
            foreach (DataGridViewColumn column in dataGridView.Columns)
            {
                // Check if the header text is found
                if (column.HeaderText == headerText)
                {
                    columnIndex = column.Index;
                    return dataGridView.Columns[columnIndex];
                }
            }

            // Return if not found
            return dataGridViewColumn;
        }
    }
}

这将创建DataGridView的扩展方法