c# - The variable name '@VarName' has already been declared Issue -
i inserting multiple items table based on selection drop down list. when select 1 item drop down works fine when select multiple items error
the variable name '@compname' has been declared. variable names must unique within query batch or stored procedure.
what doing wrong? here code
protected void dv_test_iteminserting(object sender, detailsviewinserteventargs e) { foreach (listitem listitem in cblcustomerlist.items) { if (listitem.selected) { string name= listitem.value; sqlcon.open(); string compname= ((textbox)dv_test.findcontrol("txtcompname")).text.tostring(); string num = ((textbox)dv_test.findcontrol("txtnum")).text.tostring(); sqlcommand cmd = new sqlcommand("select compnamefrom mytable compname= '" + compname+ "' , num = '" + num + "' , name= '" + name+ "' ", sqlcon); sqldatareader dr = cmd.executereader(); if (dr.read()) { lblmsg.text = "not valid"; } else { dr.close(); sqlcmd.commandtext = "insert mytable(compname, num, name) values(@compname, @num, @name)"; sqlcmd.parameters.add("@compname", sqldbtype.varchar).value = compname; sqlcmd.parameters.add("@num", sqldbtype.varchar).value = num; sqlcmd.connection = sqlcon; sqlcmd.executenonquery(); dv_test.changemode(detailsviewmode.insert); sqlcon.close(); } sqlcon.close(); } } }
you adding paramters @compname
, @num
query every time through loop.
you need move call add
outside loop , use following update them:
sqlcmd.parameters["@compname"].value = compname; sqlcmd.parameters["@num"].value = num;
so code becomes:
sqlcmd.commandtext = "insert mytable(compname, num, name) values(@compname, @num, @name)"; sqlcmd.parameters.add("@compname", sqldbtype.varchar); sqlcmd.parameters.add("@num", sqldbtype.varchar); foreach (listitem listitem in cblcustomerlist.items) { if (....) { .... } else { dr.close(); sqlcmd.parameters["@compname"].value = compname; sqlcmd.parameters["@num"].value = num; sqlcmd.connection = sqlcon; sqlcmd.executenonquery(); dv_test.changemode(detailsviewmode.insert); sqlcon.close(); } }
Comments
Post a Comment