简体   繁体   中英

How can I get the value of a given column for the selected row in a DataGridView?

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?

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
        }

    }
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();
    }
}

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..

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM