【问题标题】:How do I get the selected row data from a data grid view using SelectedRows?如何使用 SelectedRows 从数据网格视图中获取选定的行数据?
【发布时间】:2023-03-19 22:09:01
【问题描述】:

我有一个要在数据网格视图控件中显示的表。用户从控件中选择一行并按下按钮。我需要从该行中检索单元格并将它们存储为字符串。

究竟如何使用 SelectedRow 方法获取数据?我已经为此工作了几个小时,但我已经走到了尽头。这是我尝试过的一个例子:

DataGridViewCellCollection selRowData = dataGridView1.SelectedRows[0].Cells;

如果我尝试访问 selRowData[x],返回值不包含我的数据。

【问题讨论】:

标签: c# .net datagridview


【解决方案1】:

您已经接近了 - 您需要通过其索引引用每个 Cell 并返回其 Value 属性:

string firstCellValue = dataGridView1.SelectedRows[0].Cells[0].Value;
string secondCellValue = dataGridView1.SelectedRows[0].Cells[1].Value;

等等

【讨论】:

    【解决方案2】:

    如果您想要数据并且数据可能绑定到数据源,那么我建议您从选择中获取密钥,然后您可以使用它以任何您喜欢的方式访问数据:

    dataGridView.SelectedDataKey.Value;
    

    【讨论】:

      【解决方案3】:

      尝试使用 dgv 的 Item 元素。

      dgvFoo.Item(0, dgvFoo.CurrentRow.Index).Value
      

      这将返回第一项的值。您可以将其放入 for 循环中以获取所有内容。

      另一种选择是在对象上使用 SelectedRows 集合并遍历每个选定的行(或在您的情况下仅遍历一个)。

      【讨论】:

        【解决方案4】:

        好吧,没有 datagridview Item 属性..@Jay Riggs 解决方案更好...以下解决方案也有效:

        string firstCellValue = dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString();
        string secondCellValue = dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString();
        

        这里 0 是第一列,dataGridView1.CurrentRow.Index 是当前行,从中获取值。

        【讨论】:

          【解决方案5】:

          也许这是一个更合适的解决方案,使用单击的行的单元格值:

          private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
          {
            if (e.RowIndex > -1)
            {
              var val = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
            }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-03-27
            • 2012-08-08
            • 1970-01-01
            • 1970-01-01
            • 2012-08-15
            • 1970-01-01
            相关资源
            最近更新 更多