Insert data in GridView using database (SQL)

Insert the data from the textbox into the gridview using the database in ASP.NET

Step 1: Start the sql server and create the database and table in it,for this we write the command in sql like.


Hear abc is the name of the database and student is the name of the table,the attributes of this table are id,name and address.

Step 2: Firstly open the visual studio 2010 then click the File->new->web site->select the ASP.NET website.As shown in the following figure.


Step 3: The design window get appears,add three label control,three textbox control, one button and a gridview,Just like the following window.


You can change the format of the gridview by clicking on the AutoFormat option which appears when we click on the arrow of the gridview.

Step 4: Now double click on the button control to write the source code of its click event.

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 Default2 : System.Web.UI.Page


    SqlConnection con = new SqlConnection("server=.;database=abc;uid=sa;pwd=wintellect");

    SqlDataAdapter da;

    SqlCommand cmd;

    DataSet ds = new DataSet();

    protected void Page_Load(object sender, EventArgs e)


        if (!IsPostBack)





    public void show()


        da = new SqlDataAdapter("select * from student", con);


        GridView1.DataSource = ds;



    protected void Button1_Click(object sender, EventArgs e)


        string str = "insert into student values(@id,@name,@address)";

        cmd = new SqlCommand(str,con);

        cmd.Parameters.AddWithValue("@id", TextBox1.Text);

        cmd.Parameters.AddWithValue("@name", TextBox2.Text);

        cmd.Parameters.AddWithValue("@address", TextBox3.Text);





        Response.Write("Record inserted");




Step 5: Run the application by pressing F5 keys and insert the value in the textboxes then click on the button.The values that we enter in the textboxes are inserted in the gridview.

The output is as follow.