How to get cell value of DataGridView by column name?

陌路散爱 提交于 2019-11-28 23:13:23

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"]
Serg

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)

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

If you look about :

row.Cells["xxx"].Value;

By this :

row.Cells[yourdataGridView.Columns["xxx"].Index].Value;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!