How to get cell value of DataGridView by column name?
Asked Answered
N

9

27

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?

Nickelsen answered 18/11, 2012 at 1:15 Comment(1)
If you set the column's "Name" property it does work. I stumbled about this because I had several grids on my form and did not yet set the column names on the grid I was just testing. :)Aplomb
P
29

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))
    {
        // ...
    }
 }
Paganini answered 18/11, 2012 at 1:54 Comment(5)
can simply get the xxx index in the helper and use it, right?Cook
private int indexOf( DataGridView dgv, string name) { return dgv.Columns[name].Index; } foreach (DataGridViewRow row in Rows) { if (object.Equals(row.Cells[indexOf(dgv, "xxx"].Value, 123)) { // ... } }Cook
I like this solution because it is super extensible! I needed to get the value with DataPropertyName because my header text was changed to make the table more readable. This helper function works straightforwardly, just need to replace HeaderText with DataPropertyName.Cattish
how would this be in VB.NET?Intercessory
In VB the entry by Dominique Mathieu works: row.Cells(yourdataGridView.Columns("xxx").Index).ValueFugger
C
14

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.

Contraband answered 9/12, 2013 at 15:43 Comment(0)
C
14

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"]
Clotilda answered 9/3, 2016 at 4:25 Comment(0)
V
6

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)
Vulgarism answered 24/10, 2013 at 6:36 Comment(0)
L
3

if you grid column in design mode. then column name was gridView~~~Column controls's name example :

DataGridViewTextBoxColumn idDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();

idDataGridViewTextBoxColumn.Name = "idDataGridViewTextBoxColumn";

then you can access right this, you want.

row.Cells["idDataGridViewTextBoxColumn"].Value
Leitmotiv answered 9/6, 2015 at 14:59 Comment(0)
F
2

If you look about :

row.Cells["xxx"].Value;

By this :

row.Cells[yourdataGridView.Columns["xxx"].Index].Value;
Farley answered 14/3, 2019 at 13:41 Comment(0)
L
0

If your datagridviews columns are dynamic with dedicated headertext, then you can assign a name to that particular column of DGV like this:

dataGridView2.Columns[1].HeaderText = "Invoice No";
dataGridView2.Columns[1].Name = "invoice_no";

and then can use that name as an index like this :

foreach (DataGridViewRow row in rows_with_checked_column)
{
    MessageBox.Show(row.Cells["invoice_no"].Value.ToString());
}
Lightship answered 6/7, 2021 at 18:47 Comment(0)
R
0

You can also try it under the DataGridview cell click event

         TxtTankPainting.Text = DataGridTransfData.Rows[e.RowIndex].Cells["TankPainting"].Value.ToString();
                TxtTankPosition.Text = DataGridTransfData.Rows[e.RowIndex].Cells["TankPosition"].Value.ToString();
                TxtCorePosition.Text = DataGridTransfData.Rows[e.RowIndex].Cells["CorePosition"].Value.ToString();
Rhinarium answered 24/10, 2021 at 13:8 Comment(0)
T
0

I am using EF6 and my DataGridView is bound to a list of entities.
My data looks like:
public partial class orders : IEntity { }
var lstOrders = new List<orders>();
bindingSource.DataSource = lstOrders;
In this case there is a 'DataBoundItem' containing the entity with all its field names and field values. So I could access the field by name this way:
var orderNr = ((orders)dgv1.Rows[e.RowIndex].DataBoundItem).orderNr;

Thimbleful answered 18/6 at 17:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.