2014-09-20 27 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; 
     } 
      }