C#: 从DataGridView中选择行

8

我有一个包含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。另外,如何确保用户只选择一行而不是多行?这段代码看起来正确吗?


1
你不需要遍历DataGrid的所有行来获取第一个SelectedRow。在这里使用foreach循环是浪费时间的。 - Iñaki Elcoro
6个回答

26

2
我必须使用dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - mack

1

如果只选择了整行才可以使用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();
}

1
您可以将网格类比为数组进行引用:
ProductsGrid[ProductsGrid.SelectedColumns[0].Index, ProductsGrid.SelectedRows[0].Index].Value;

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

您可以通过设置 DataGridView 上的 MultiSelect 属性来锁定用户仅选择单个行。或者,您可以使 CellClick 事件执行:

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

1

好的,您不需要同时迭代网格中的所有行并访问SelectedRows集合。如果跳过迭代并使用SelectedRows集合,则您的问题可能是选择模式不正确:

必须将SelectionMode属性设置为FullRowSelect或RowHeaderSelect,才能使用SelectedRows属性填充所选行。

(来自MSDN


0

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


0

你也可以使用.BoundItem


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接