GidView连续插入多条记录的问题
出现的错误提示:(程序已通过编译了,执行时出错的)
变量名 '@code ' 已声明。变量名在批查询或存储过程内部必须唯一。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.Data.SqlClient.SqlException: 变量名 '@code ' 已声明。变量名在批查询或存储过程内部必须唯一。
源错误:
行 77: SqlDataSource1.InsertParameters.Add( "zglb ",TypeCode.String, GridView2.Rows[i].Cells[3].Text);
行 78: SqlDataSource1.InsertParameters.Add( "text ",TypeCode.String, GridView2.Rows[i].Cells[4].Text);
行 79: SqlDataSource1.Insert();
行 80: // Response.Write(zglb + text);
行 81: //Response.Write(this.GridView2.Rows[i].Cells[3].Text + this.GridView2.Rows[i].Cells[4].Text + " <br /> ");
源文件: d:\anjzNET\ks1\Jd_1Add.ascx.cs 行: 79
代码:
protected void Button1_Click(object sender, EventArgs e)
{
CheckBoxList CheckBoxList1 = new CheckBoxList();
for (int i = 0; i < this.GridView2.Rows.Count; i++)
{
CheckBoxList1 = ((CheckBoxList)this.GridView2.Rows[i].FindControl( "CheckBoxList1 "));
if (CheckBoxList1.Items[0].Selected)
{
SqlDataSource1.InsertCommand = "Insert into jd_1(code,code_id,zglb,text) Values(@code,@code_id,@zglb,@text) ";
SqlDataSource1.InsertParameters.Add( "code ", TypeCode.String, GridView1.Rows[GridView1.SelectedIndex].Cells[3].Text);
SqlDataSource1.InsertParameters.Add( "code_id ", TypeCode.String, GridView1.Rows[GridView1.SelectedIndex].Cells[4].Text);
SqlDataSource1.InsertParameters.Add( "zglb ",TypeCode.String, GridView2.Rows[i].Cells[3].Text);
SqlDataSource1.InsertParameters.Add( "text ",TypeCode.String, GridView2.Rows[i].Cells[4].Text);
SqlDataSource1.Insert();
//Response.Write(this.GridView2.Rows[i].Cells[3].Text + this.GridView2.Rows[i].Cells[4].Text + " <br /> ");
}
}
[解决办法]
在1.1的时候对一个数据库存储过程操作的时候
都是先new parameter(类型,长度,id)
然后在加入到command的sqlparameter里面去并且赋值
类似的建议你在for循环外先对要加入到sqldatasource的insertparameter进行定义,然后加入到sqldatasource的insertparameter中来(但不赋值),先定义也就是new一下
然后在for循环里面定位到相应的参数进行赋值,每次赋值前SqlDataSource1.InsertParameters.Clear();一下
你看看这样能不能实现你要的效果?我没有用过,所以上面是猜测,不一定正确