C#:从 DataGridView 中选择行

标签 c# winforms datagridview

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

最佳答案

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

关于C#:从 DataGridView 中选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2741084/

相关文章:

c# - 如何在 WebBrowser 控件中注入(inject) CSS

c - WinAPI 组合框问题 - 按案例跳过

c# - DataGridViewComboBoxColumn 中的选定项始终检索第一个值

c# - 我想以编程方式在 C# 中生成对 DataGridView 行的单击

c# - 打开 xml 从 .pptx 文件获取图像

c# - Lucene.net 和部分 "starts with"词组搜索

c# - DataGridView HeaderCell 为数字类型时不显示值

c# - 从受密码保护的 Zip 文件中提取

c# - 如何在 winform 中关闭所有打开的对话框的主窗体

c# - 如何将datagridview中的值存储到集合类C#