当前位置: 代码迷 >> ASP.NET >> 问一简单有关问题:怎么更新DataSet里的数据
  详细解决方案

问一简单有关问题:怎么更新DataSet里的数据

热度:5680   发布时间:2013-02-26 00:00:00.0
问一简单问题:如何更新DataSet里的数据?
用userAdapter.Fill(userDataSet)把数据弄到DataSet里了,我现在想把数据改动然后再存回数据库里,怎么做?

------解决方案--------------------------------------------------------
//利用CommandBuilder更新数据库

//添加记录
public void Insert()
{
SqlConnection oConn = DBClass.Conn;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand( "select * from [Student] ",oConn );
SqlCommandBuilder cmdBld = new SqlCommandBuilder( da );

oConn.Open();

da.Fill(dt);
DataRow dRow = dt.NewRow();
dRow[ "Name "] = Name.Text;
dRow[ "Age "] = Age.Text;
dRow[ "Address "] = Address.Text;
dRow[ "CreatedTime "] = Time.Text;
dt.Rows.Add(dRow);
da.Update(dt.Select( null,null,DataViewRowState.Added ) );

oConn.Close();
}

//删除记录
public void Delete()
{
SqlConneciton oConn = DBClass.Conn;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand( "select * from [Student] where Id= "+Id,oConn );
SqlCommandBuilder cmdBld = new SqlCommandBuilder( da );

oConn.Open();

da.Fill(dt);
dt.Rows[0].Delete();
da.Update(dt.Select( null,null,DataViewRowState.Deleted ) );

oConn.Close();

}


//修改记录
public void Update()
{
SqlConnection oConn = DBClass.Conn;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand( "select * from [Student] where Id= "+Id,oConn );
SqlCommandBuilder cmdBld = new SqlCommandBuilder( da );

oConn.Open();

da.Fill(dt);

dt.Rows[0][ "Name "] = Name.Text;
dt.Rows[0][ "Age "] = Age.Text;
dt.Rows[0][ "Address "] = Address.Text;
dt.Rows[0][ "CreatedTime "] = Time.Text;
da.Update(dt.Select( null,null,DataViewRowState.ModifiedCurrent ) );

oConn.Close();
}
  相关解决方案