mysql - C# how to insert data in SQL table and setting an empty string into 0 -
i'm using sql code insert data table
"insert electric values('" + date.text + "', '" + h1.text + "', '" + h2.text + "', '" + h22.text + "', '" + h3.text + "', '" + h4.text + "', '" + h5.text + "', '" + h6.text + "', '" + h7.text + "', '" + h8.text + "', '" + h9.text + "', '" + h10.text + "');"
sometimes leave textboxes empty , int. won't insert table. the error set column default 0 still wont insert. default
please me solve problem. thanks
try :
using(sqlconnection connection = new sqlconnection(yourconnectionstring)) { string query = "insert electric (h1, h2, h3, h4) values (@h1, @h2, @h3, @h4)"; using(sqlcommand command = new sqlcommand(query, connection)) { int h1data = 0; int32.tryparse(h1textbox.text, out h1data); int h2data = 0; int32.tryparse(h2textbox.text, out h2data); int h3data = 0; int32.tryparse(h3textbox.text, out h3data); int h4data = 0; int32.tryparse(h4textbox.text, out h4data); command.parameters.addwithvalue("@h1", h1data); command.parameters.addwithvalue("@h2", h2data); command.parameters.addwithvalue("@h3", h3data); command.parameters.addwithvalue("@h4", h4data); connection.open(); int result = command.executenonquery(); // check error if(result < 0) { // error } } }
explain :
the textboxs should ints said if not error occurs !
now easy, create int var , textbox content .. default int var equal 0 , use tryparse if textbox content isn't number, conversion wouldn't completed int var still have default value 0 , inserted database (the same occurs empty textbox or empty string).
you may need edit work want,
i hope helps .. luck !
Comments
Post a Comment