C# Datagridview - 选中检查行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12432627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:16:11  来源:igfitidea点击:

C# Datagridview - Check Row is Selected

c#winformsdatagridview

提问by hshah

I have this code in my C# program, but it throws a fit when some buttons are clicked because there is no row selected in the DataGridView (I use the ClearSelection method):

我在我的 C# 程序中有这段代码,但是当点击某些按钮时它会抛出一个合适的错误,因为在 DataGridView 中没有选择行(我使用 ClearSelection 方法):

string selectedUser = usersGrid.SelectedRows[0].Cells[1].Value.ToString();

Is there some sort of check I can do before the above line to ensure that a row is selected?

在上述行之前是否可以进行某种检查以确保选择了一行?

采纳答案by Tergiver

if (usersGrid.SelectedRows.Count > 0)

回答by MethodMan

I am going to take a stab at what I think you are trying to do, try this below

我将尝试一下我认为您正在尝试做的事情,请在下面尝试

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

also do the following as well and checkout the link

也执行以下操作并查看链接

Set DataGridView.MultiSelect=false and DataGridView.SelectionMode= FullRowSelect. This will make it so the user can only select a single row at a time.

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