0

Knowing the name of the column to be queried, how can I extract the value from that column for the currently selected record in a DataGridView?

IOW, if I have a DataGridView with columns named id, Date, Time, Space, and I want the value of the Space column for the currently selected row, how can I assign that value to a String variable?

In pseudocode, I would expect it to be something like:

String s = dataGridView1.CurrentRow["Space"].ToString();

...but I'm sure it's not really that straightforward.

UPDATE

The answers look good, but is there a way to get the value from the current row that doesn't respond to a dataGridView event? I need to assign the value apart from the dataGridView being clicked or any other event. IOW: is there a way to get the current row?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

4 Answers4

1

In the Grid_RowDataBound event

    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem == null)
            return;

        DataRowView row = e.Row.DataItem as DataRowView;

        if(row["Space"] != null)
        {
            string s = row["Space"].ToString();
            //do stuff
        }

    }
mybirthname
  • 17,949
  • 3
  • 31
  • 55
1
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
    {
       string s = dataGridView1.Rows[e.RowIndex].Cells["Space"].Value.ToString();
    }
}
1

You can use

dataGridView1.CurrentRow.Cells[yourColumn] 

to access the current row if there is one.. ..and even if you have MultiSelect on, you can always use

dataGridView1.SelectedRows[0].Cells[yourColumn] 

to access the first selected row..

TaW
  • 53,122
  • 8
  • 69
  • 111
  • Cool; this is a more straightforward way than my step-by-step idea; simply "String colVal = dataGridView1.CurrentRow.Cells[colName]; – B. Clay Shannon-B. Crow Raven Oct 05 '14 at 14:27
  • Yes. Please check on the [MSDN](http://msdn.microsoft.com/de-de/library/system.windows.forms.datagridview.currentrow%28v=vs.110%29.aspx) docs; you'll see a) how to set the currentrow and b) that there may not be a row 'current'! – TaW Oct 05 '14 at 14:32
0

I reckon this will work:

private string GetCurrentOrFirstValOfColumn(string colName)
{
    String colVal = String.Empty;
    DataGridViewRow dgvr = dataGridViewFileContents.CurrentRow;
    if (null != dgvr.Cells[colName].Value)
    {
        colVal = dgvr.Cells[colName].Value.ToString();
    }
    return colVal;
}
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862