2013-03-07 125 views
0

我想通過C#中的窗體按鈕更新我的數據庫。當我運行我將要顯示的代碼時,它不顯示任何錯誤,但它不會更改數據庫或數據網格中的數據。更新按鈕不起作用

private void update_Click(object sender, EventArgs e) 
{ 
    SqlConnection NewCon = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ASPNET\cd\cdcwk2\cddatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); 
    SqlCommand cmd = new SqlCommand("UPDATE cdstock set cd_title='" + cdtext.Text + "', artist='" + artisttext.Text + "',genre='" + genretext.Text + "', rating=" + ratingtext.Text + ", cd_discription='" + distext.Text + "' where cd_id =" + idtext.Text + ";", NewCon); 
    MessageBox.Show("UPDATE cdstock set cd_title='" + cdtext.Text + "', artist='" + artisttext.Text + "',genre='" + genretext.Text + "', rating='" + ratingtext.Text + "', cd_discription='" + distext.Text + "' where cd_id ='" + idtext.Text + "'"); 

    NewCon.Open(); 

    cmd.ExecuteNonQuery(); 

    NewCon.Close(); 
    MessageBox.Show("Record Has Now Been UPDATED!!"); 

} 
+0

您是否嘗試過手動運行顯示的查詢? – 2013-03-07 13:33:14

+0

您是否使用SQL Management Studio或其他SQL客戶端運行生成的commang? – 2013-03-07 13:33:31

+1

'cmd.ExecuteNonQuery();'返回什麼? – 2013-03-07 13:34:10

回答

0

嗨我發現瞭解決方案,它現在工作正常,謝謝你的時間。解決方案如下。

   String NewCon = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ASPNET\cd\cdcwk2\cddatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; 

     SqlConnection con = new SqlConnection(NewCon); 
     SqlCommand cmd = new SqlCommand(); 

     cmd.CommandText = "UPDATE cdstock set cd_title='" + cdtext.Text + "', artist='" + artisttext.Text + "',genre='" + genretext.Text + "', cd_discription='" + distext.Text + "', rating=" + ratingtext.Text + " where cd_id = " + dataGridView1.CurrentRow.Cells[0].Value; 
     cmd.Connection = con; 
     cmd.Connection.Open(); 

     cmd.ExecuteNonQuery(); 
     cmd.Connection.Close(); 

cddatabaseDataSet3.GetChanges(); this.cdstockTableAdapter.Fill(this.cddatabaseDataSet3.cdstock);

 MessageBox.Show("Record Has Now Been UPDATED!!");