2016-04-03 22 views
0

我想從鏈接到數據庫中的表格的DataGridView中刪除選定的行。它指出以下錯誤代碼。從數據網格中選擇一行SQL刪除語句不起作用

enter image description here

與我要去的地方錯在這裏的任何想法?

刪除按鈕代碼

private void DeleteExtraBtn_Click(object sender, EventArgs e) 
{ 
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True"); 
    con.Open(); 
    try 
    { 
     //Delete selected extra row  
     SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = @Extra_ID", con); 
     sda.Parameters.AddWithValue("@ExtraID", extraGridView.CurrentRow.Cells[0]); 
     sda.ExecuteNonQuery(); 

    } 
    catch(Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 


    con.Close(); 
    loadExtraTable(); 
} 

回答

1

我沒有看到你在任何地方執行命令。

添加;

sda.ExecuteNonQuery(); 

此外,您正在引用單元格對象,而不是它的值。 此外,您引用@ExtraID@Extra_ID

private void DeleteExtraBtn_Click(object sender, EventArgs e) 
{ 
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True"); 
    con.Open(); 
    try 
    { 
     //Delete selected extra row  
     SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = @ExtraID", con); 
     sda.Parameters.AddWithValue("@ExtraID", extraGridView.CurrentRow.Cells[0].Value); 
     sda.ExecuteNonQuery(); 
    } 
    catch(Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 


    con.Close(); 
    loadExtraTable(); 
} 
+0

哦,是的,道歉。我沒有把它包含在上面的例子中。但它仍然沒有與此工作。 –

+1

你應該爲良好的實踐事項包裝你的連接和命令使用塊,以便更容易清理。你有沒有檢查過騙局?如果它沒有打開,它不會拋出一個錯誤。 – Wobbles

+0

顯示我剛剛添加到上面的代碼中的錯誤。 –

-1

什麼是 「ExtraId」,一個文本框,一個字符串?

根據這一點,你必須使用:

SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = @" + Extra_ID.Text, con); 
+0

我現在添加了錯誤代碼的表現。 –