Click here to Skip to main content
15,887,326 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i get the error
<pre>'ExecuteScalar: Connection property has not been initialized.'

if you have other suggestion please specify

What I have tried:

this is what i tried
controller
 string constring = ConfigurationManager.ConnectionStrings["DbContext"].ToString();
            SqlConnection con = new SqlConnection(constring);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "SELECT MAX(Product_Code)+1 As Product_Code FROM Add_Product";
            con.Open();
            ViewBag.name = cmd.ExecuteScalar().ToString();
            con.Close();
            DBContext DB = new DBContext();
Create View
<pre>   @Html.TextBox("txtTitle", (string)ViewBag.name)
Posted
Updated 1-Nov-20 1:50am
Comments
Richard Deeming 2-Nov-20 10:18am    
NB: Your code suggests that you are trying to pre-allocate a sequential number for the next record. If you have multiple users using your application at the same time - and you will! - they'll all end up trying to insert the same record.

Use an IDENTITY column or a SEQUENCE instead, which will insert the next number when the record is saved.

1 solution

The error message is telling you the command doesn't have a connection.

SqlCommand cmd = new SqlCommand();
cmd.Connection = con; // add this
 
Share this answer
 
Comments
Property Of Praveen pop 1-Nov-20 9:44am    
error is cleared but i couldn't display value from database into textbox
F-ES Sitecore 1-Nov-20 10:26am    
There's nothing particularly wrong with the code so check the ViewBag.name has the data you expect.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900