【问题标题】:C#: Select row from DataGridViewC#:从 DataGridView 中选择行
【发布时间】:2010-04-29 22:01:40
【问题描述】:

我有一个带有 DataGridView(3 列)和一个按钮的表单。每次用户单击按钮时,我都希望获取存储在该行第一列中的值。

这是我的代码:

    private void myButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in ProductsGrid.Rows)
        {
            if (this.ProductsGrid.SelectedRows.Count == 1)
            {
             // get information of 1st column from the row
             string value = this.ProductsGrid.SelectedRows[0].Cells[0].ToString();
            }
        }
    }

但是,当我单击 myButton 时,this.ProductsGrid.SelectedRows.Count 为 0。另外,如何确保用户只选择一行而不是多行? 这段代码看起来对吗?

【问题讨论】:

  • 您不需要遍历 (foreach) DataGrid 的所有行来仅获取第一个 SelectedRow。 foreach 循环在这里是浪费时间。

标签: c# winforms datagridview


【解决方案1】:

设置DataGridView.MultiSelect=false 和DataGridView.SelectionMode = FullRowSelect。这将使用户一次只能选择一行。

【讨论】:

  • 我不得不使用 dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
【解决方案2】:

SelectedRows 仅在选择了整行时才返回行(如果需要,您可以在 datagridview 上打开 RowSelect)。更好的选择是使用SelectedCells

private void myButton_Click(object sender, EventArgs e)
{
    var cell = this.ProductsGrid.SelectedCells[0];
    var row = this.ProductsGrid.Rows[cell.RowIndex];
    string value = row.Cells[0].Value.ToString();
}

【讨论】:

    【解决方案3】:

    好吧,您不需要遍历网格中的所有行并访问 SelectedRows 的集合。如果您跳过迭代并使用 SelectedRows 集合,那么您的问题可能是不正确的 SelectionMode:

    必须设置 SelectionMode 属性 到 FullRowSelect 或 RowHeaderSelect 对于 SelectedRows 属性是 填充了选定的行。

    (来自MSDN

    【讨论】:

      【解决方案4】:

      可以像数组一样引用网格:

      ProductsGrid[ProductsGrid.SelectedColumns[0].Index, ProductsGrid.SelectedRows[0].Index].Value;
      

      通过从 SelectedRowsCollection 和 SelectedColumnsCollection 的第一个索引中选择索引,如果选择了多行,您将获取第一个值。


      您可以通过在 DataGridView 上设置 MultiSelect 属性来锁定用户只选择一行。或者,您可以执行 CellClick 事件:

      ProductsGrid.ClearSelection();
      ProductsGrid.Rows[e.RowIndex].Selected = true;
      

      【讨论】:

        【解决方案5】:

        SelectedRows.Count 返回当前选中的整行数。您可能想使用SelectedCells.Count

        【讨论】:

          【解决方案6】:

          您也可以使用.BoundItem

          【讨论】:

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