C#:从DataGridView中选择行

Bi.*_*Bi. 6 c# datagridview winforms

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

这是我的代码:

    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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*pth 23

设置DataGridView.MultiSelect = false和DataGridView.SelectionMode = FullRowSelect.这样就可以使用户一次只能选择一行.

  • 我不得不使用dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; (2认同)