2013-12-16 141 views
0

正如您在此代碼中看到的,我正在更新Button1_Click處的數據集ds,並且想要將對該數據集所做的更改更新到數據庫。 如果我把它寫在Button1_Click它是工作,但是當我把完全相同的代碼在Unnamed1_Click它不工作,我不知道爲什麼!從數據集中更新數據庫

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.Configuration; 
using System.Data; 
using System.Data.SqlClient; 

public partial class Discount : System.Web.UI.Page 
{ 

    DataSet ds = new DataSet(); 

    public void Page_Load(object sender, EventArgs e) 
    { 
     using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9")) 
     { 
      SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Items", con); // יצירת dataAdapter 
      da.Fill(ds); 
      GridView2.DataSource = ds; 
      GridView2.DataBind(); 
     } 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     int price; 
     for (int i = 0; i < GridView2.Rows.Count; i++) 
     { 

      if (Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]) > Convert.ToInt32(minamount.Text)) 
      { 
       price = Convert.ToInt32(ds.Tables[0].Rows[i][2]); 
       price -= price * int.Parse(discountrate.Text)/100; 
       ds.Tables[0].Rows[i][2] = Convert.ToString(price); 
      } 
     } 


     GridView2.DataSource = ds.Tables[0]; 
     GridView2.DataBind(); 

     //SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_"); 
     //con.Open(); 
     //SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con); 
     //SqlCommandBuilder builder = new SqlCommandBuilder(tmpda); 
     //tmpda.Update(ds); 
    } 

    protected void Unnamed1_Click(object sender, EventArgs e) 
    { 
     using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_86098")) 
     { 
      con.Open(); 
      SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con); 
      SqlCommandBuilder builder = new SqlCommandBuilder(tmpda); 
      tmpda.Update(ds); 
     } 

    } 
} 

回答

0

您需要爲您的SqlDataAdapter指定更新命令。只需插入下面的代碼你CommandBuilder的instace後:

tmpda.UpdateCommand = builder.GetUpdateCommand(); 
+0

它仍然沒有工作:( –

+0

您點擊Unnamed1按鈕之前對您的數據集的更改或者,您在做一個插入/刪除你的數據集? – candeias