c# - 从 C# 中的 DataGridView 获取选定行的第一个单元格

标签 c# datagridview

我有一个连接到 mssql 数据库的 datagridview,我想在按 exec_cmd_btn 时从所选行中获取第一个单元格 到目前为止我已经尝试过:

private void exec_cmd_btn_Click(object sender, EventArgs e)
{
    string cell = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
}

这给我带来了以下错误:

Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index

当我按下数据 GridView 时,我需要创建一个事件吗?

最佳答案

我猜您可能会遇到 SelectedRows 属性的问题,因为这取决于 DataGridViewSelectionMode 的情况放。如果 DataGridViews SelectionMode 未设置为 FullRowSelect,则此实现将不起作用。由于您试图从第一列获取单元格,那么我认为这不会成为问题,因为您想确保也选择了第一列。另一个问题是,如果 DataGridView MultiSelect 属性设置为 true,那么使用 SelectedRows[0] 的代码将返回最后选定的行,而不是首先。如果您想要第一个选定的行,则可以使用下面的代码。它将显示所选的第一行和最后一行。希望这会有所帮助。

// The DataGridView SelectionMode must be set  'FullRowSelect' for this to work! 
private void button1_Click(object sender, EventArgs e) {
  if (dataGridView1.SelectedRows.Count > 0) {
    int firstRowIndex = dataGridView1.SelectedRows.Count - 1;
    string cell = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
    string cell2 = dataGridView1.SelectedRows[firstRowIndex].Cells[0].Value.ToString();
    MessageBox.Show("Last selected row at cell[0] value: " + cell + " First Selected row at cell[0] value: " + cell2);
  }
}

关于c# - 从 C# 中的 DataGridView 获取选定行的第一个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42734357/

相关文章:

vb.net - 将更新从 datagridview 发送到数据库中的现有行

vb.net - 将 2 列数据表的值与空格连接,并在 vb.net 中将 "-"替换为空

c# - 结合表单例份验证和基本身份验证

c# - 通过IP地址选择域 Controller C#

c# - 如何使用 MongoDB 2.0 进行更新插入?

c# - 在使用 DataTable 作为其数据源时,如何指定 DataGridView 选择使用的列类型

c# - 表,SQL C# 通过在 datagridview 中选择一行将数据添加到 "FK table"

c# - 在 C# 中,如何将 Intellisense 添加到 DataGridView 单元格?

c# - 免注册 com dll 要求安装 .net Framework 3.5,而注册后它工作正常

c# - Type.GetType() 和 Assembly.GetType() 返回不同的结果