Search code examples
c#datagridviewdatagridviewcolumnheadertext

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


How do I get a column of a data grid view by the header text rather than by the index or name property?

What I tried so far is the my intuitive approach:

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

dataGridViewColumn = dataGridView.Columns[myHeaderText];

however this returns

Object reference not set to an instance of an object.

Solution

  • It is returning

    Object reference not set to an instance of an object.
    

    because

    dataGridViewColumn = dataGridView.Columns[myHeaderText];
    

    is looking for a column in the the dataGridView with a Name Property = myHeaderText not HeaderText property. To get around this you could try the following:

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

    this creates an extension method to DataGridView