2014-09-20 25 views
0

C#Windows窗体获取选定的dataGridView列数据?

我有一个按钮,从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(); 

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

回答

0

删除行后,您无法获得值。所以改变你的代码这样

//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); 
+0

谢谢,它的工作原理! – user3888775 2014-09-20 08:04:03

+0

@ user3888775欢迎 – Sathish 2014-09-20 08:52:56

0

这是错误的逻辑。

由于该行已经通过RemoveAt移除()去掉,

你不能从dataGridView1.SelectedRows得到错误的行[0]。

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; 
     } 
      }