【问题标题】:How can I get the value of a given column for the selected row in a DataGridView?如何获取 DataGridView 中选定行的给定列的值?
【发布时间】:2014-10-05 04:17:09
【问题描述】:

知道要查询的列的名称,如何从该列中提取 DataGridView 中当前选定记录的值?

IOW,如果我有一个包含名为 id、Date、Time、Space 的列的 DataGridView,并且我想要当前选定行的 Space 列的值,我如何将该值分配给 String 变量?

在伪代码中,我希望它是这样的:

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

...但我敢肯定这并不是那么简单。

更新

答案看起来不错,但有没有办法从不响应 dataGridView 事件的当前行获取值?除了被单击的 dataGridView 或任何其他事件之外,我还需要分配值。 IOW:有没有办法获取当前行?

【问题讨论】:

    标签: c# datagridview datagridviewcolumn


    【解决方案1】:

    你可以使用

    dataGridView1.CurrentRow.Cells[yourColumn] 
    

    访问当前行,如果有的话.. ..即使您启用了 MultiSelect,您也可以随时使用

    dataGridView1.SelectedRows[0].Cells[yourColumn] 
    

    访问第一个选定的行..

    【讨论】:

    • 酷;这比我一步一步的想法更直接;简单地说“字符串 colVal = dataGridView1.CurrentRow.Cells[colName];
    • 是的。请查看MSDN 文档;您将看到 a) 如何设置 currentrow 和 b) 可能没有“当前”行!
    【解决方案2】:
    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();
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        我认为这会奏效:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多