简体   繁体   English

仅使用数据集更新数据库不会插入

[英]Updating database using dataset only updates doesn't insert

I have a grid view in asp.net which I am populating like this: 我在asp.net中有一个网格视图,其填充如下:

     sda1 = new SqlDataAdapter("select * from tran_dtls where tc='" + tcdropDown.SelectedValue + "'and doc_no='" + DocNoTxt.Text + "'", con);
     build = new SqlCommandBuilder(sda1);
     sda1.Fill(ds);                      //ds is a data set
     GridView1.DataSource = ds;
     GridView1.DataBind();

I update the grid view by passing the ds to a new data table, adding a new row in datatable then again binding the datatable to the grid: 我通过将ds传递到新的数据表来更新网格视图,在数据表中添加新行,然后再次将数据表绑定到网格:

       dt = (DataTable)ViewState["myViewState"];
              dt = ds.Tables[0];
              dr = dt.NewRow();
              dr["TC"] = Session["TC"];
              dr["sr_no"] = Session["i"].ToString(); //I have more fields but for simplicity only displaying few
              dt.Rows.Add(dr);
              dt.AcceptChanges();
              ViewState["myViewState"] = dt;

              Session["gridRow"] = dt;

Everything is smooth uptil now ,but when I try to update the database(after inserting new entries in the dataset) it doesn't work the save button code is below: 现在一切都顺利进行,但是当我尝试更新数据库(在数据集中插入新条目之后)不起作用时,保存按钮代码如下:

 protected void onSaveClick(object sender, EventArgs e)
    {


        dt = (DataTable)Session["gridRow"];// I am passing the data table in a session    as I am entering the new entry from a pop up window
        dt.GetChanges(DataRowState.Modified);


        sda1.Fill(dt);

        sda1.Update(dt);   
    }

Funny part is when I edit a the existing entry in dt it does edit(classic sql update) but it never insert any new entries which are added in the data table ,and it doesn't even throw a error 有趣的是,当我在dt中编辑现有条目时,它会进行编辑(经典sql更新),但它永远不会插入数据表中添加的任何新条目,甚至不会引发错误

This line 这条线

dt.AcceptChanges(); 

marks all rows in the datatable as Unchanged. 将数据表中的所有行标记为“不变”。

When you call 你打电话时

dt.GetChanges(DataRowState.Modified); 

you get only the rows modified after the AcceptChanges() 您只能在AcceptChanges()之后修改行

Moreover, to get the rows Added to the database the correct statement will be 此外,要获得添加到数据库中的行,正确的语句将是

dt.GetChanges(DataRowState.Added); 

but, as I have said, this will return nothing due to the AcceptChanges() call. 但是,正如我已经说过的那样,由于AcceptChanges()调用,该方法不会返回任何内容。
You should remove the AcceptChanges() statement. 您应该删除AcceptChanges()语句。
Also, I don't think you need to call this in the logic of the save button 另外,我认为您无需按照“保存”按钮的逻辑来调用它

sda1.Fill(dt);    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM