Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cell value of DataGridView by column name?

Tags:

I have a WinForms application with a DataGridView, which DataSource is a DataTable (filled from SQL Server) which has a column of xxx. The following code raises the exception of

ArgumentException was unhandled. Column named xxx cannot be found.

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

Is it possible to get the cell values by column name?

like image 740
ca9163d9 Avatar asked Nov 18 '12 01:11

ca9163d9


3 Answers

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))     {         // ...     }  } 
like image 189
Patrick Quirk Avatar answered Sep 21 '22 22:09

Patrick Quirk


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"]
like image 34
JfredoJ Avatar answered Sep 22 '22 22:09

JfredoJ


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.

like image 25
Richard Hansell Avatar answered Sep 24 '22 22:09

Richard Hansell