How to get cell value of DataGridView by column name?

DataGridViewColumn objects have a Name (shown only in the forms designer) and a HeaderText (shown in the GUI at the top of the column) property. The indexer in your example uses the column's Name property, so since you say that isn't working I assume you're really trying to use the column's header.

There isn't anything built in that does what you want, but it's easy enough to add. I'd use an extension method to make it easy to use:

public static class DataGridHelper
{
    public static object GetCellValueFromColumnHeader(this DataGridViewCellCollection CellCollection, string HeaderText)
    {
        return CellCollection.Cast<DataGridViewCell>().First(c => c.OwningColumn.HeaderText == HeaderText).Value;            
    }
}

And then in your code:

foreach (DataGridViewRow row in Rows)
{
    if (object.Equals(row.Cells.GetCellValueFromColumnHeader("xxx"), 123))
    {
        // ...
    }
 }

Yes, just remove the quotes and add .Index, i.e.

foreach (DataGridViewRow row in Rows)
{
    if (object.Equals(row.Cells[xxx.Index].Value, 123)) 

...that is if your column is really called xxx and not some other name like Column1, etc. You can set the column name and the column header independantly so check in the designer.


By doing this you will be able to access the cell at the "xxx" column name for the currently selected row.

dataGridView1.SelectedRows[0].Cells["xxx"]

I found this:

  1. Right mouse click on the datagridview.
  2. Select from popup menu "Edit columns".
  3. Select column that you want. Design/(Name) - it's what you were looking for.

Sample:

if(dataGridViewProjectList.Rows[dataGridViewProjectList.CurrentCell.RowIndex].Cells["dateendDataGridViewTextBoxColumn"].Value.ToString().Length == 0)