//datagridview初始化方法
private void dgvHeadInit(int id) { string sql1 = @"select id, worktimeNo as 工序代码, initialCount as 起始针数, seamDistance as 车缝距离, endCount as 落回针数, initialCount+seamDistance+endCount as [每小时指标(件)], worktimeName as 工序名称, samTime as SAM值, target AS 工序指标, equipment as 使用设备, tool as 使用工具, pid from product_desProductTime where pid=" + id + " and positation='头部' and fno='"+txtfNo.Text+"'"; SqlConnection cn = new SqlConnection("server=172.20.50.4;uid=sa;pwd=p4japo020;database=gsd"); sda1 = new SqlDataAdapter(sql1, cn); ds1 = new DataSet(); sda1.Fill(ds1); ds1.Tables[0].TableName = "product_desProductTime"; dgvHead.DataSource = ds1.Tables[0]; dgvHead.Columns["id"].Visible = false;
}
//更新数据源的方法 private int UpdateByDataSet(DataSet ds, string strTblName, string strconn) { try { SqlConnection cn = new SqlConnection(strconn); SqlDataAdapter sda = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(@"select id, worktimeNo as 工序代码, initialCount as 起始针数, seamDistance as 车缝距离, endCount as 落回针数, worktimeName as 工序名称, samTime as SAM值, target AS 工序指标, equipment as 使用设备, tool as 使用工具, pid from " + strTblName + "", cn); sda.SelectCommand = cmd; SqlCommandBuilder cb = new SqlCommandBuilder(sda); sda.Update(ds1,strTblName); return 0; } catch (Exception ee) { MessageBox.Show(ee.ToString()); return -1; } }
//保存按钮:更新操作(主表和子表) private void btnSave_Click(object sender, EventArgs e) { //int id = 0; //保存到数据库之前先判断一下主表是否有重复记录 string fno = txtfNo.Text.Trim(); string fname = txtPname.Text.Trim(); int orderqty = Convert.ToInt32(txtOrderQty.Text); double orderc = Convert.ToDouble(txtOrderCoefficient.Text); Image pic = pbchef.Image; int flag = 2; flag= UpdateByDataSet(ds1, "product_desProductTime",strconn); }
请问这段代码有什么问题??为什么数据源无法更新??谢谢
数据库表:
desProductAttach表和product_desProductTime表,前一个是主表,后一个是子表,子表pid就是主表的id
string constr = "server=localhost\\sqlserver2008;initial catalog=test;uid=sa;pwd=123456;"; SqlConnection conn = new SqlConnection(constr); //设置select查询命令,SqlCommandBuilder要求至少有select命令 SqlCommand selectCMD = new SqlCommand("select top 0 SNo,SName,SAge from Student", conn); DataTable dt = new DataTable(); SqlDataAdapter sda = new SqlDataAdapter(selectCMD); //上面的语句中使用select 0,不是为了查询出数据,而是要查询出表结构以向DataTable中填充表结构 sda.Fill(dt); //给DataTable添加10条记录 for(int i=1;i<=10;i++) dt.Rows.Add(new object[] { i, "aaa"+i, 20+i }); SqlCommandBuilder scb = new SqlCommandBuilder(sda); //执行更新 sda.Update(dt.GetChanges()); //使DataTable保存更新 dt.AcceptChanges();
http://www.cnblogs.com/moss_tan_jun/archive/2011/11/26/2263992.html
自己参考吧
UpdateByDataSet()方法里面,if(true)是死循环.去掉吧,不知道是恶作剧还是咋的
你要使用UpdateCommand,然后SqlCommand的语句写update语句
我所实现的功能是:在一个datagridview中进行修改,这个修改是包括增加和更新的,请问这个应该用哪个???
@wq_vincent: 要我说还是纯手写代码得了,就像走路,你这种不了解内部实现原理的就开始跑,要摔跤的
要修改就用update 表 set 某某=值 增加就用insert语句 ,详情你可以去看 http://www.w3school.com.cn/sql/sql_update.asp