SqlCommandBuilder 删除与更新的用法,附代码, 与 dataGridView 结合
using System.Data.SqlClient;
private void toolStripButton2_Click(object sender, EventArgs e) //保存
{
if (dataGridView1.Rows.Count == 0) return;
string con = string.Empty;
string str_sql = string.Empty;
str_sql = "SELECT [产品编号] ,[产品特性] ,[号头],[制令类别] ,[每串数量] ,[串数] ,[框],[数量] FROM 收容数对应 where 1=2"; //只有结构,没有数据
dtsve = SQL.command(str_sql).Tables[0];
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataRow drow = dtsve.NewRow();
drow["产品编号"] = dataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
drow["产品特性"] = dataGridView1.Rows[i].Cells[1].Value.ToString().Trim();
drow["号头"] = dataGridView1.Rows[i].Cells[2].Value.ToString().Trim();
drow["制令类别"] = dataGridView1.Rows[i].Cells[3].Value.ToString().Trim();
drow["每串数量"] = dataGridView1.Rows[i].Cells[4].Value.ToString().Trim();
drow["串数"] = dataGridView1.Rows[i].Cells[5].Value.ToString().Trim();
drow["框"] = dataGridView1.Rows[i].Cells[6].Value.ToString().Trim();
drow["数量"] = dataGridView1.Rows[i].Cells[7].Value.ToString().Trim();
dtsve.Rows.Add(drow); //以下三行不可少写,漏写
DS = new DataSet();
DataTable Ldt = dtsve.Copy();
DS.Tables.Add(Ldt);
}
con = "Server = (local)//SQLEXPRESS;database = PCMIS;user = sa;pwd = Z950+!@f";//本地数据库服务器
//con = "Server = 192.168.2.22;database = PCMIS;user = sa;pwd = Z950+!@f";//公司专用服务器
SqlConnection conn = new SqlConnection(con);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [产品编号] ,[产品特性] ,[号头],[制令类别] ,[每串数量] ,[串数] ,[框],[数量] FROM 收容数对应 where 1=2", conn);
adapter.DeleteCommand = new SqlCommand("delete from 收容数对应 where "+str1, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
conn.Open();
adapter.DeleteCommand.ExecuteNonQuery();//删除数据
if (DS.Tables.Count != 0)
{
adapter.Update(DS); //更新数据
}
{
adapter.Update(DS); //更新数据
}
conn.Close();
}