2014-05-06 20 views
0

我正在开发一个应用程序,我想从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

+0

您更新的数据库将位于'bin'目录中。检查数据库。 –

回答

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和更新方法需要使用Insert/update/Delete命令对数据库执行这些操作。我使用SqlcommandBuilder来生成插入/更新/删除,Student表必须有主键来使用SqlcommandBuilder生成插入/更新/删除命令。

+0

我用你的代码,但仍然没有得到更新的数据库.. –

+0

是否有任何错误? – Harikant

+0

这就是问题..没有错误。仍然显示第7行,但数据库仍未显示插入的行。 –