An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll - C# visual studio -


i've got code lines, when try save data data base shows error:

an unhandled exception of type 'system.invalidoperationexception' occurred in system.data.dll

additional information: executenonquery: propriedade connection não foi inicializada.

can guys give little ?

sqlconnection cn = new sqlconnection(@"data source=(localdb)\v11.0;attachdbfilename=c:\basededadospap.mdf;integrated security=true;connect timeout=30");         sqlcommand cmd = new sqlcommand();  private void button1_click(object sender, eventargs e)         {              if (textbox4.text != "" & textbox2.text != "")             {                 {                     using (var connection = new sqlconnection(@"data source=(localdb)\v11.0;attachdbfilename=c:\basededadospap.mdf;integrated security=true;connect timeout=30"))                     {                         cn.open();                         cmd.commandtext = "insert artigo (nomeartigo,preco) values ('" + textbox4.text + "','" + textbox2.text + "')";                         cmd.executenonquery();                         cmd.clone();                         messagebox.show(" artigo inserido com sucesso! ");                         this.close();                     }                 }             }         } 

its because didn't tell command use connection try this:

sqlcommand cmd = new sqlcommand(     "query string",     cn); 

you have tell command connection use query data. see connection named cn, have pass sqlcommand constructor.

so full code like:

using (sqlconnection con = new sqlconnection(@"data source=(localdb)\v11.0;attachdbfilename=c:\basededadospap.mdf;integrated security=true;connect timeout=30")) {     con.open();     sqlcommand cmd = new sqlcommand("select top 3 * dogs1 order weight", con);     cmd.executenonquery();     cmd.clone();     messagebox.show(" artigo inserido com sucesso! ");     this.close(); } 

do notice how passed sql command connection variable?


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -