获取所选数据GridView列数据



C#Windows窗体

我有一个从dataGridView中删除所选行的按钮。我还希望该按钮检索所选行的"ordre"列值,这样我就可以在从sql表中删除顺序的查询中使用它。

以下是我的代码:

                    dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
                    //SQL connection
                    SqlConnection con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
                    SqlCommand command = con.CreateCommand();
                    //SQL QUERY
                    command.CommandText = "DELETE FROM bestillinger WHERE ordrenr = @ordre";
                    command.Parameters.AddWithValue("@ordre",dataGridView1.SelectedRows[0].Cells["ordre"].Value.ToString())
                    con.Open();
                    var ordre = command.ExecuteScalar();
                    con.Close();

但它不起作用!没有记录被删除

删除行后,无法获取值。所以像这个一样更改你的代码

 //SQL connection
SqlConnection con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt 
+ "," + globalvariables.porttxt + "\SQLEXPRESS;Database=ha;Persist Security
Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
//SQL QUERY
command.CommandText = "DELETE FROM bestillinger WHERE ordrenr = @ordre";
command.Parameters.AddWithValue("@ordre",dataGridView1.
SelectedRows[0].Cells["ordre"].Value.ToString())
con.Open();
var ordre = command.ExecuteScalar();
con.Close();
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);

这是错误的逻辑。

由于该行已被RemoveAt()删除,

不能从dataGridView1.SelectedRows[0]中获取错误的行。

我想你想要这个。

  private void grdform1_CellClick(object sender, DataGridViewCellEventArgs e)
         {  
         If(e.ColumnIndex==0 ||e.ColumnIndex==1)
          {
           txtshowcolunm.text=e.ColumnIndex;
              }
            else
            {
          txtshowcolunm.text=e.ColumnIndex;
        }
           }

最新更新