Skip to content

October 12, 2013 using a form to insert data into an sql server connecting via Connection strings in web.config file

Requerment :

Need to code connect string in web config.

Need to execute insert query using this connection..

Benefit of Connection strings in web.config file

Get easy access to sql connection to all web page,easy to edit the connection.

Step to Do:

  • Step 1: Open a new blank project in Visual Studio.
  • Step 2: Setup the connection string in webconfig.
  • Step 3:Add a new web form an write the needed name space .
  • Step 4: Create a new object for sql connection ,then access the connection string in webconfig using the ConfigurationManager Class.
  • Step 5:Drag and drop the input element such as textbox to the form from the design view for receiving the data for execution of insert query.
  • Step 6:Create a new object for SqlCommand since we need to execute the sql query.
  • Step 7:Connecting the SqlCommand object to sql connection object ..Since SqlCommand need a valid connection credentials to Sql Server.
  • Step 8:Next we passing the query string to SqlCommand object using the SqlCommand.CommandText Property 
  • Step 9:Passing the the data from input form element (textbox) to SqlCommand object using the Parameters.AddWithValue Method.
  • Step 10: Since we need to execute the process only after we open the connection ,after opening  we write ExecuteNonQuery Method
  • Step 11: After executing the process we need to close the connection.
  • Step 12 : we place code block in Step 10 and step 11 in a try{  statements in  Step 10 and step 11 } (try-catch ),This is to handle Exception ,If any exception occur the code will move to catch section,skipping the try section.In our code we put to display the error details in catch section using a  label in web form.


Code in Web Config File :


    <add name="CresignsysConnectionString" connectionString="Data Source=.;Initial Catalog=EEE_Dept;Persist Security Info=True;User ID=sa;Password=admin" providerName="System.Data.SqlClient"/>

C# Code For  insert data into an sql server 



Download the Code


Similar References

Connection string in web.config file



Read more from C#.NET