SystemInvalidOperationException

J'essaye de sauver ceci à ma database mais je continue à get cette erreur

System.InvalidOperationException 

voici mon code.

  protected void btnSend_Click(object sender, EventArgs e) { con.Open(); cmd = new SqlCommand(@"INSERT INTO orders2 (orderName,orderFile,orderType,orderPrice,orderQuantity,orderShipped) VALUES ('"+DropDownList1.SelectedValue+"','"+lblFile.Text+"','"+lblPrice.Text+"','"+txtQuantity.Text+"','"+DateTime.Now+"')",con); cmd.ExecuteNonQuery(); con.Close(); lblFinished.Text = "Order has been submitted for process."; } 

WhoAmI probablement raison, mais votre code pourrait être grandement amélioré pour éviter d'autres problèmes et vous permettre également de ne pas autoriser les exceptions non gérées.

J'ai mis des commentaires supplémentaires directement dans le code:

 try { // SqlConnection is disposable, so it is recommended to dispose it (using calls Dispose() for you) using (var con = new SqlConnection(connStr)) { con.Open(); // this is missing from your code and might the errors actual cause // SqlCommand is also disposable using (var cmd = con.CreateCommand()) { // is is strongly recommended to construct parameterized commands // to avoid SQL injection (check this - https://technet.microsoft.com/en-us/library/ms161953(v=sql.105).aspx) cmd.Text = @" INSERT INTO orders2 (orderName,orderFile,orderType,orderPrice,orderQuantity,orderShipped) VALUES (@orderName, @orderFile, @orderType, @orderPrice, @orderQuantity, @orderShipped)"; // the parameters - SqlCommand infers parameter type for you cmd.AddWithValue("@orderName", DropDownList1.SelectedValue); cmd.AddWithValue("@orderFile", lblFile.Text); cmd.AddWithValue("@orderType", theMissingParametersForOrderType); // some conversion might be needed here, as I expect the price to be some number // with a fixed number of decimals // eg Convert.ToDecimal(lblPrice.Text) cmd.AddWithValue("@orderPrice", lblPrice.Text); // same convertion issue as for price cmd.AddWithValue("@orderQuantity", txtQuantity.Text); cmd.AddWithValue("@orderShipped", DateTime.Now); } } } // there are several Exceptions that can be raised and treated separately // but this at least you can do catch (Exception exc) { // log the error somewhere // put a breakpoint just below to inspect the full error details } // this is executed even if an exception has occurred finally { if (con != null && con.State != ConnectionState.Closed) con.Close(); } 

En remarque, ce code appartient à une couche de données, pas de couche de présentation. Pensez à l'inclure dans un autre assemblage.

Vous insérez ici 6 valeurs ( orderName,orderFile,orderType,orderPrice,orderQuantity,orderShipped ), mais seulement 5 valeurs. DropDownList1.SelectedValue, lblFile.Text, lblPrice.Text, txtQuantity.Text, DateTime.Now .