This article shows how to insert data into a database using ASP.Net C# and a Stored Procedure. I used several textboxes and a button. When the user clicks on the “Insert” button the data is saved into the database.
INITIAL CHAMBER
Step 1
Open your Visual Studio 2010 and create an Empty Website, provide a suitable name (insert_demo).
Step 2
In Solution Explorer you get your empty website, then add a Web Form and SQL Server Database as in the following.
For Web Form:
insert_demo (Your Empty Website) then right-click then select Add New Item -> Web Form. Name it insertdata_demo.aspx.
For SQL Server Database:
insert_demo (Your Empty Website) then right-click then select Add New Item -> SQL Server Database. (Add the database inside the App_Data_folder.)
DATABASE CHAMBER
Step 3
In Server Explorer, click on your database (Database.mdf) then select Tables -> Add New Table. Make the table like this:
Table -> tbl_data (Don't Forget to make ID as IS Identity -- True)
Figure 1: Data Table
Make one Stored Procedure for inserting data into the database, by going to database.mdf then seelct Store Procedures then right-click then select Add New Store Procedure.
Sp_insert
Figure 2: Sp Insert
DESIGN CHAMBER
Step 4
Now make some design for your application by going to insertdata_demo.aspx and try the code like this.
insertdata_demo.aspx
Your design will look like this:
Figure 3: Design Page
CODE CHAMBER
Step 5
Now it's time for server-side coding so that our application works. Open your insertdata_demo.aspx.cs file and code it as in the following.
insertdata_demo.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- public partial class _Default: System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- SqlConnection con = new SqlConnection(@
- "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
- SqlCommand cmd = new SqlCommand("sp_insert", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("name", TextBox1.Text);
- cmd.Parameters.AddWithValue("email", TextBox2.Text);
- cmd.Parameters.AddWithValue("education", TextBox3.Text);
- cmd.Parameters.AddWithValue("phoneno", TextBox4.Text);
- cmd.Parameters.AddWithValue("city", TextBox5.Text);
- con.Open();
- int k = cmd.ExecuteNonQuery();
- if (k != 0) {
- lblmsg.Text = "Record Inserted Succesfully into the Database";
- lblmsg.ForeColor = System.Drawing.Color.CornflowerBlue;
- }
- con.Close();
- }
- }
OUTPUT CHAMBERFigure 4: Output
Figure 5: Insert Data
Figure 6: Save Data
I hope you like it, thank you for the reading. Have a good Day.