问题描述
protectedvoidButton2_Click(objectsender,EventArgse){SqlConnectioncoon=newSqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);stringinsetpp="insertintoshijuan(kemuid,shijuanname,shijuanss)values(1,'"+TextBox1.Text+"',1)";intafid=GetIDInsert(insetpp);if(afid!=0){foreach(GridViewRowdrinGridView1.Rows){stringsingle="insertintoshijuanxiangxi(shijuanid,type,shitiid,fenshu)values("+afid+",'单选题',"+int.Parse(((Label)dr.FindControl("label3")).Text)+","+int.Parse(TextBox3.Text)+")";Insert(single);}}}publicintGetIDInsert(stringXSqlString){intCount=0;SqlConnectioncoon=newSqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);coon.Open();SqlCommandcmd=newSqlCommand(XSqlString,coon);Count=int.Parse(cmd.ExecuteScalar().ToString().Trim());coon.Close();returnCount;}publicintInsert(stringXSqlString){intCount=-1;SqlConnectioncoon=newSqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);coon.Open();SqlCommandcmd=newSqlCommand(XSqlString,coon);Count=cmd.ExecuteNonQuery();coon.Close();returnCount;}}
解决方案
解决方案二:
cmd.ExecuteScalar()的结果是个对象objectxs=cmd.ExecuteScalar();应该先判断是否为空intrslt=0;if(xs==null){rslt=0;}else{rslt=int.Parse(rslt.Trim());}
解决方案三:
你的SQL是Insert,这时对应的应该是ExecuteNonQueryExecuteScalar是用于Select的
解决方案四:
然后如果你要获取新增后的id,那么你的insertsql后面还需要加句select,然后两句之间以分号做间隔insertxxxx;select@@identity
解决方案五:
不好意思,我没怎么懂。那个数据已经添加到数据库,但是点击保存按钮就有刚刚那个问题