-1

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.
G. LC
  • 794
  • 1
  • 8
  • 27
  • You can use lambda or a simple loop but the result may be null or non-unique..: `int index = -1; string column = "xyz"; var cols = dataGridView1.Columns.Cast().Where(x => x.HeaderText == column).ToList(); if (cols.Count == 1) index = cols.First().Index;` – TaW Aug 01 '18 at 22:23

1 Answers1

-1

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

G. LC
  • 794
  • 1
  • 8
  • 27