簡體   English   中英

如何獲取DataGridView中選定行的給定列的值?

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

知道要查詢的列的名稱后,如何從該列中提取DataGridView中當前選定記錄的值?

IOW,如果我有一個名為id,Date,Time,Space的DataGridView列,並且我想要當前選定行的Space列的值,如何將該值分配給String變量?

用偽代碼,我希望它類似於:

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

...但是我敢肯定這並不是那么簡單。

更新

答案看起來不錯,但是有沒有辦法從不響應dataGridView事件的當前行中獲取值? 除了需要單擊的dataGridView或任何其他事件之外,我需要分配值。 IOW:有沒有辦法獲取當前行?

Grid_RowDataBound事件中

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

您可以使用

dataGridView1.CurrentRow.Cells[yourColumn] 

訪問當前行(如果有)....即使打開了MultiSelect,也可以始終使用

dataGridView1.SelectedRows[0].Cells[yourColumn] 

訪問第一行。

我認為這可以工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM