如何通过 HeaderText 属性 获取 DataGridViewColumn?

How to get a DataGridViewColumn by it's HeaderText Property?

如何通过 header 文本而不是索引或名称 属性 获取数据网格视图的列?

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

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

dataGridViewColumn = dataGridView.Columns[myHeaderText];

然而这returns

Object reference not set to an instance of an object.

正在返回

Object reference not set to an instance of an object.

因为

dataGridViewColumn = dataGridView.Columns[myHeaderText];

正在 dataGridView 中查找具有 Name 属性 = myHeaderText 而非 HeaderText [=26= 的列].要解决此问题,您可以尝试以下操作:

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 创建了一个扩展方法