有时候遇到这样的情况,用户在客户端编辑数据,添加数据.然后整体更新到数据库里面
数据库结构:
CREATE TABLE [Test_Base] (
[CodeZZB] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[InterName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
[Guid] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_LoginPerson_Guid] DEFAULT (newid()),
CONSTRAINT [PK_Test_Base] PRIMARY KEY CLUSTERED
(
[CodeZZB]
) ON [PRIMARY]
) ON [PRIMARY]
GO
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
定义 全局DataSet
DataSet ds=new DataSet();读取数据
private void button1_Click(object sender, System.EventArgs e)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
//
string str_Conn="workstation id=JHTCHINA;packet size=4096;user id=sa;initial catalog=master;persist security info=False";
try
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
SqlConnection objConn=new SqlConnection(str_Conn);
string str_sql="select * from Test_Base";
SqlCommand objComm=new SqlCommand(str_sql,objConn);
SqlDataAdapter objAdapter=new SqlDataAdapter(objComm);
objAdapter.Fill(ds,"Test_Base");
dataGrid1.DataSource=ds;
}
catch (Exception exc)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
MessageBox.Show(exc.Message);
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
编辑添加dataGrid以后更新数据
private void button2_Click(object sender, System.EventArgs e)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
try
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
//这里ds.Table[0]里面的数据已经改变
string str_Conn="workstation id=JHTCHINA;packet size=4096;user id=sa;initial catalog=master;persist security info=False";
//整体把修改的数据更新到数据库里面
SqlConnection objConn=new SqlConnection(str_Conn);
string str_sql="select * from Test_Base";
SqlCommand objComm=new SqlCommand(str_sql,objConn);
SqlDataAdapter objAdapter=new SqlDataAdapter(objComm);
SqlCommandBuilder updataBulid=new SqlCommandBuilder(objAdapter);
objAdapter.Update(ds,"Test_Base");
MessageBox.Show("OK");
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}
catch (Exception exc)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
MessageBox.Show(exc.Message);
}
}
运行通过
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
如果是整体添加,在数据读取的时候
string str_sql="select * from Test_Base where 1=2";
一句代码就可以了