windows 如何在c#.net windows应用程序中检查gridview的行是否被选中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6174975/
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-09-15 16:57:30  来源:igfitidea点击:

how to check whether gridview's row is selected or not in c#.net windows application

c#.netwindowsgridview

提问by Amruta

I want to know how to check whether a gridview's row got selected or not. I am working on windows application.

我想知道如何检查 gridview 的行是否被选中。我正在开发 Windows 应用程序。

I want to put a if condition ie if a particular row gets selected then fill the textbox with the correspoding cell value.

我想放置一个 if 条件,即如果选择了特定行,则用相应的单元格值填充文本框。

I am just not getting the way how to give the condition in the if clause.

我只是不知道如何在 if 子句中给出条件。

回答by Akram Shahda

Handle the DataGridView.SelectionChangedevent. Use the DataGridView.SelectedRowsproperty to get the selected rows collection.

处理DataGridView.SelectionChanged事件。使用DataGridView.SelectedRows属性获取选定的行集合。

private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
    // Update the text of TextBox controls.
    textBox1.Text = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
    textBox2.Text = dataGridView.SelectedRows[0].Cells[2].Value.ToString();
    ....
}

回答by Akram Shahda

Check DataGridViewRow.Selectedproperty.

检查DataGridViewRow.Selected属性。

if (dataGridView.Rows[rowIndex].Selected)
{
    // Do something ..
}

回答by FIre Panda

Check the selected property of DataGridViewRow, it returns truefor selected else false.

检查 的 selected 属性DataGridViewRow,它返回trueselected else false

bool isSelected = dataGridView1.Rows[e.RowIndex].Selected;

回答by Alex R.

You can subscribe to the SelectionChanged event of the control and iterate through each selected row if multi-selection is enabled or just the first one if single-row selection only.

如果启用了多选,您可以订阅控件的 SelectionChanged 事件并遍历每个选定的行,或者如果仅单行选择,则只遍历第一个。

private void MyGridView_SelectionChanged(object sender, EventArgs e)
{
      for (int i = 0; i < MyGridView.SelectedRows.Count; i++)
      {
          MyTextBox.Text = MyGridView.SelectedRows[i].Cells[0].Value.ToString(); //assuming column 0 is the cell you're looking for

          // do your other stuff
      }
}

More information can be found on the SelectedRowsproperty.

更多信息可以在SelectedRows属性中找到。