c# - The SqlParameterCollection only accepts non-null SqlParamter type objects, not String objects -
sqlcommand cmd = con.createcommand(); cmd.commandtext = "insert records ([student id], [first name], [last name], " + "[middle initial], gender, address, status, year, email, course, " + "[contact number]) values ( @student id, @first name, @last name, " + "@middle initial, @gender, @address, @status, @year, @email, " + "@course, @contact number)"; sqlparameter p1 = new sqlparameter("@[student id]", sqldbtype.int); p1.value = textbox1.text; cmd.parameters.add("1"); sqlparameter p2 = new sqlparameter("@first name", sqldbtype.varchar); p2.value = textbox2.text; cmd.parameters.add("p2"); sqlparameter p3 = new sqlparameter("@last name", sqldbtype.nvarchar); p3.value = textbox3.text; cmd.parameters.add("p3"); sqlparameter p4 = new sqlparameter("@middle initial", sqldbtype.nchar); p4.value = combobox1.text; cmd.parameters.add("p4"); sqlparameter p5 = new sqlparameter("@gender", sqldbtype.nchar); p5.value = combobox2.text; cmd.parameters.add("p5"); sqlparameter p6 = new sqlparameter("@address", sqldbtype.varchar); p6.value = textbox4.text; cmd.parameters.add("p6"); sqlparameter p7 = new sqlparameter("@status", sqldbtype.nchar); p7.value = combobox3.text; cmd.parameters.add("p7"); sqlparameter p8 = new sqlparameter("@year", sqldbtype.varchar); p8.value = combobox4.text; cmd.parameters.add("p8"); sqlparameter p9 = new sqlparameter("@email", sqldbtype.varchar); p9.value = textbox5.text; cmd.parameters.add("9"); sqlparameter p10 = new sqlparameter("@course", sqldbtype.varchar); p10.value = combobox5.text; cmd.parameters.add("p10"); sqlparameter p11 = new sqlparameter("@contact number", sqldbtype.varchar); p11.value = textbox6.text; cmd.parameters.add("p11"); cmd.executenonquery(); con.close();
add instance of parameter collection, not string "p11"
sqlparameter p11 = new sqlparameter("@contactnumber", sqldbtype.varchar); p11.value = textbox6.text; cmd.parameters.add(p11);
and don't need make life difficult spaces in parameter names.
sqlcommand cmd = con.createcommand(); cmd.commandtext = "insert records ([student id], [first name], [last name], " + "[middle initial], gender, address, status, year, email, course, " + "[contact number]) values ( @studentid, @firstname, @lastname, " + "@middleinitial, @gender, @address, @status, @year, @email, " + "@course, @contactnumber)"; ..... // name parameters without spaces sqlparameter p1 = new sqlparameter("@studentid", sqldbtype.int); p1.value = textbox1.text; cmd.parameters.add(p1); .....
the parameters placeholders inside command text replaced value of parameter same name, no need complicate things adding spaces inside parameter placeholder.
Comments
Post a Comment