使用DataSet插入记录

时间:2014-05-06 08:37:23

标签: c# asp.net sql ado.net

我正在开发一个应用程序,我想在其中插入DataSet中的数据。

以下是我的插入数据的代码:

WebForm1.aspx.cs中:

 public void Recieve_Data()
    {
        DataGridView.DataSource = obj.Get_Data();
        DataGridView.DataBind();
    }

    public void Insert_Data()
    {
       TextBox StudentID = DataGridView.FooterRow.FindControl("TxtID") as TextBox;
       TextBox StudentName = DataGridView.FooterRow.FindControl("TxtName") as TextBox;
       TextBox StudentSex = DataGridView.FooterRow.FindControl("TxtSex") as TextBox;
       TextBox StudentCity = DataGridView.FooterRow.FindControl("TxtCity") as TextBox;

       int StuID = Convert.ToInt32(StudentID.Text);
       string StuName = StudentName.Text;
       string StuSex = StudentSex.Text;
       string StuCity = StudentCity.Text;

       obj.Insert_Data(StuID, StuName,StuSex, StuCity);          
       Recieve_Data();
    }

我的Insert_Data()是:

public void Insert_Data(int StuID, string StuName, string StuSex, string StuCity)
    {
        adap = new SqlDataAdapter("select * from Student", con);
        DataSet ds = new DataSet();
        adap.Fill(ds,"Student");

        DataRow dr = ds.Tables[0].NewRow();
        dr["ID"] = StuID;
        dr["Name"] = StuName;
        dr["Sex"] = StuSex;
        dr["City"] = StuCity;
        ds.Tables[0].Rows.Add(dr);
        ds.Tables[0].AcceptChanges();
    }

我最后在数据集中成功接收到新的插入记录(第七条记录):

enter image description here

但是在数据库中,我的表没有更新第七行:

enter image description here

1 个答案:

答案 0 :(得分:0)

public void Insert_Data(int StuID, string StuName, string StuSex, string StuCity)
{
    adap = new SqlDataAdapter("select * from Student", con);
    SqlCommandBuilder cmdBuilder=new SqlCommandBuilder(adap);
    DataSet ds = new DataSet();
    adap.Fill(ds,"Student");

    DataRow dr = ds.Tables[0].NewRow();
    dr["ID"] = StuID;
    dr["Name"] = StuName;
    dr["Sex"] = StuSex;
    dr["City"] = StuCity;
    ds.Tables[0].Rows.Add(dr);
    ds.Tables[0].AcceptChanges();
    adap.Update(ds, "Student"); 
}

//注意:要在DB中反映这些更改,您必须调用SqlDataAdapter的“Update”方法,并且更新方法需要使用Insert / update / Delete命令在DB上执行这些操作。我使用SqlcommandBuilder生成Insert / update / Delete,Student表必须有主键才能使用SqlcommandBuilder生成insert / update / delete命令。