Inserting New Row in GridView in 2.0


1) Create the simple web application ( with C#).


2) Create new table (User) in your database.

Column Name Data Type
UserId int (Pk and AutoIncrement)
UserName varchar(50)
Address1 varchar(50)
EmailAddress varchar(50)

3) In your application (.aspx file) put the below code. we have first true the property of gridview (ShowFooter) and put the asp control in to the FooterTemplate. put the one label for display message.Here I not implement the edit command.

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="UserID"
                CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True">
                    <asp:TemplateField HeaderText="UserID" InsertVisible="False" SortExpression="UserID">
                            <asp:Label ID="lblUserID" runat="server" Text='<%# Eval("UserID") %>'></asp:Label>
                    <asp:TemplateField HeaderText="UserName" SortExpression="UserName">
                            <asp:TextBox ID="txtUserName" runat="server" Text='<%# Bind("UserName") %>'></asp:TextBox>
                            <asp:Label ID="lblUserName" runat="server" Text='<%# Eval("UserName") %>'></asp:Label>
                        <asp:TextBox ID="txtfooterUserName" runat="server"></asp:TextBox>
                        <%-- Here we Put the RequiredFieldValidator for textbox (txtfooterUserName) --%>
                        <asp:RequiredFieldValidator ID="rfvUserName" runat="server" ControlToValidate="txtfooterUserName" ErrorMessage="*"></asp:RequiredFieldValidator>
                    <asp:TemplateField HeaderText="Address1" SortExpression="Address1">
                            <asp:TextBox ID="txtAddress1" runat="server" Text='<%# Bind("Address1") %>'></asp:TextBox>
                            <asp:Label ID="lblAddress1" runat="server" Text='<%# Eval("Address1") %>'></asp:Label>
                        <asp:TextBox ID="txtfooterAddress1" runat="server"></asp:TextBox>
                    <asp:TemplateField HeaderText="EmailAddress" SortExpression="EmailAddress">
                            <asp:TextBox ID="txtAddress1" runat="server" Text='<%# Bind("EmailAddress") %>'></asp:TextBox>
                            <asp:Label ID="lblEmailAddress" runat="server" Text='<%# Eval("EmailAddress") %>'></asp:Label>
                        <asp:TextBox ID="txtfooterEmailAddress" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfvEmailAddress" runat="server" ControlToValidate="txtfooterEmailAddress" ErrorMessage="*"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="revEmailAddress" runat="server" ControlToValidate="txtfooterEmailAddress" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
                    ErrorMessage="Please Enter Valid Email Address" ></asp:RegularExpressionValidator>
                    <asp:TemplateField HeaderText="EditRecord">
                            <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                            <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                            <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                        <asp:LinkButton ID="lnkInsert" runat="server" Text ="Insert" OnClick="lnkInsert_Click"></asp:LinkButton>
                <FooterStyle BackColor="Silver" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#EFF3FB" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <EditRowStyle BackColor="#2461BF" />
                <AlternatingRowStyle BackColor="White" />
<asp:Label ID="lblMessage" runat="server" Text ="Insert Record Successfully" Visible ="false" > </asp:Label>

4) Open Code Behind File and on the page load event put the below code.

protected void Page_Load(object sender, EventArgs e)
        //check whether page is postback or not
        //if page is not postback at that time we bind the gridview
        if (!Page.IsPostBack)
          //call the function BindGridView

    public void BindGridView()
        //here write connection string
        string strsql = DBConnection.sqlstr;

        //create object for sqlconnection
        SqlConnection sqlcon = new SqlConnection(strsql);

        //here i use the query
        //create the object of sqlcommand
        SqlCommand sqlcmd = new SqlCommand("select * from [User]", sqlcon);

        //create sqldataadapter object and give the sqlcommand as parameter
        SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
        //declare the dataset
        DataSet ds = new DataSet();
        //fill dataset using fill method of SqlDataAdapter

        //bind the GridView1
        GridView1.DataSource = ds.Tables[0];



5) On Click Event of the Insert button put the below code or directly paste below code.

protected void lnkInsert_Click(object sender, EventArgs e)
        string strsql = DBConnection.sqlstr;

        //create object for sqlconnection
        SqlConnection sqlcon = new SqlConnection(strsql);

        //here i use the query
        string strQuery = "Insert into [User] (UserName,Address1,EmailAddress) values (@UserName,@Address1,@EmailAddress)";
        //create the object of sqlcommand
        SqlCommand sqlcmd = new SqlCommand(strQuery, sqlcon);
        //find the footer row for UserName And Assign the value
        sqlcmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50).Value = ((TextBox)GridView1.FooterRow.FindControl("txtfooterUserName")).Text;
        sqlcmd.Parameters.Add("@Address1", SqlDbType.VarChar, 50).Value = ((TextBox)GridView1.FooterRow.FindControl("txtfooterAddress1")).Text;
        sqlcmd.Parameters.Add("@EmailAddress", SqlDbType.VarChar, 50).Value = ((TextBox)GridView1.FooterRow.FindControl("txtfooterEmailAddress")).Text;
        //open the sql connection
        // Execute the Insert Command In to Database
        //close the sqlconnection
        //if record successfully insert we display the message
        lblMessage.Visible = true;
        //bind grid view for latest record

Check Application.




  1. Sriram · · Reply

    Awesome reply…excellent stuff…! u kept it simple…

    Thanks a million…….!!!!!!!!!!

  2. Thanks For Your Motivational Comment.

    Have a gr8 day ahead.

  3. pls sent me its update row code

  4. Renu,

    sure i will post an article very soon.

  5. ANWER JAMAL · · Reply

    really so easy to understand, and very much helpful, thnnks to you and almighty ALLAH

  6. SUJIT MANDAL · · Reply

    Thanx nice article.

  7. santosh · · Reply

    This artical is very useful to me Can you plz send me the code for update and Delete button.


  8. santhosh · · Reply

    It is an very very nice one thanx for this

  9. manisha · · Reply

    what code u have given here to insert new row is good but have one doubt that if i don’t have any rows in database or dataset which i am binding at that time gridview will not display anything right.

    so what i want to know is if suppose there are no records in the database/datset then how come i insert the records in the gridview(as i know this can be done by using emptydata template).

    So can u give the idea for this (i mean inserting the record using insert button in gridview )like how it works with windows gridview application

    1. nice thought…

      actually i’ve achieved this a year ago but i had a same problem just like you..

      1. Did Anybody figure out how to add a new row when there is no data exists already?

      2. Monsignor · ·

        I’ve archived that with following code:

        /// Reload list of job titles
        public void RebindList()
        IList source = JobTitles;

        // If datasource is empty - create fake datasource with single record
        if (JobTitles.Count == 0)
        source = new List { new JobTitle() };

        // Assign datasource and bind GridView
        gvJobTitles.DataSource = source;

        // Again check whether the actual datasource is empty and if so,
        // disable showing of first row (as it contains fake data).
        // This will give you an ability to see just footer
        if (JobTitles.Count == 0)
        gvJobTitles.Rows[0].Visible = false;

      3. Vladislav M · ·

        I use footer to insert new rows in GridView. But when the GridView is empty this approach doesn’t work ((
        Does anyone know how to solve this problem?

  10. Ok, I found the solution. In the emptydata template, give the command name “EmptyInsert” for the insert button. While, the regular Insert button will have “Insert” command. In the row command event, check for command name. If it’s insert the use footer row. If it’s EmptyInsert, use gridview.control[0].control[0]… etc. You might have to use control[0] one or more time depends on your design. Once you find the textbox using controls, use the value to insert. I hope this will help somebody.

  11. Hey thanks a helped me a lot..
    thanku veryyyyyyyyyyyyyy much

  12. pardon, i wanna ask, how to display gridview just 1 row base o userId user login?? thx’s

  13. Vanchinathan · · Reply

    Thanks it is very helpful. And Edit,Delete also i need with this example. pls help me.

  14. Hi, can anyone please provide me the code for editing a row?

  15. How can we get protected void lnkInsert_Click(object sender, EventArgs e)
    event ?

  16. kalpana · · Reply

    Thank u soooooooooo much……

  17. pls can you tell me what spacename i use to debg errors like this
    “The name ‘DBConnection’ is not exist in the current context”

  18. pls can you tell me what spacename i use to debg errors like this
    “The name ‘DBConnection’ is not exist in the current context”

  19. I am not getting the values from the footer template……when i click on “inset” link.The method is getting fired but the values of the text boxes are not populated into the variables inside my “insert” method.

    Can i get quick reply……………

  20. sumitha vr · · Reply

    Really greate

  21. José · · Reply

    En página *.asp (v. studio .net 2010) tengo un gridview y en un botón (evento click) un código que hace una consulta a una tabla de una base de datos en sql server 2008. Puedo llevar el resultado de la consulta al gridview sin ningún problema.

    Resulta que necesito ubicar en el mismo gridview, un checkbox para que usuario pueda hacer click y seleccionar el registro. Esta checkbox no guarda ningún vínculo con la base de datos, solo se usa temporalmente para que los registros que se encuentren seleccionados puedan ser leídos para su correspondiente modificación que afectan a la misma y/o otra tabla.


    Mediante programación necesito ubicar el checkbox y el usuario pueda elegir.

    Mediante programación como puedo crear filas en gidview vinculados o sin vínculos a un dataset o datable.

    Mediante programación como se puede llamar: GridView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

    Mediante programación como se puede llamar: Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs).

    1. You can create dynamic event handler and do it.

  22. José · · Reply


    Ya tengo la tabla o consulta con sus registros ubicados en un gridview. Si a ese Gridview que contiene registros realizados a través de una consulta, le adiciono o modifico registros sin que estos afecten la base de datos, se puede hacer? y como?

  23. Absials · · Reply

    Hi Patriwala,
    Its a good article. But I have an issue while i am going to edit the existing rows in the gridview. The required field validators for the footer (new) row are called when i try to Update the existing rows above footer.
    Since i am not going to add new row through footer, so the footer validators should not call on clicking the Update link of the rows other than footer.
    Thanks in advance for your valuable suggestions.

    1. Gaurav Singh · · Reply

      hi this gaurav
      thanx buddy all about this

      but i have some confusion about this i have insert new record then i’ll going to edit or deleted that row which is inserted it takes before row index and deleted or edit before row…
      So please help me.Soon

  24. Hello Sir,
    I am using a gridview,in that i am using itemtemplate textbox,i want to show data in the gridview textbox from the database,i dont why the data is not coming to the gridview help me to solve the problem below is my code:

    My aspx code is:

    <asp:Label ID="label10" runat="server" Font-Bold="true" ForeColor="#BF6000" Text="”>

    <asp:TextBox ID="TxtServiceCode" Font-Bold="true" ForeColor="#BF6000" Text='’
    runat=”server” Width=”55px”>


    <asp:TextBox ID="TxtServiceName" runat="server" ReadOnly="true" Font-Bold="true" ForeColor="#BF6000" Width="150px" Text='’>

    <asp:TextBox ID="TxtServiceAmount" ReadOnly="true" Font-Bold="true" ForeColor="#BF6000" Text='’
    runat=”server” Width=”55px”>

    <asp:TextBox ID="Txtquantity" Font-Bold="true" ForeColor="#BF6000" Text='’
    runat=”server” Width=”55px”>

    <asp:TextBox ID="TxtdiscAmt" Font-Bold="true" ForeColor="#BF6000" Text='’
    runat=”server” Width=”55px”>

    <asp:TextBox ID="TxtNetAmt" ReadOnly="true" Font-Bold="true" ForeColor="#BF6000" Text='’
    runat=”server” Width=”55px”>

    My CS code is:

    DataSet dss = new DataSet();
    SqlConnection MyConnection = new SqlConnection(“server=user32;database=mydatabse;UID=sa;PWD=123;”);
    SqlDataAdapter mydataadapter = new SqlDataAdapter(“GetServCodes”, MyConnection);
    mydataadapter.SelectCommand.CommandType = CommandType.StoredProcedure;
    mydataadapter.SelectCommand.Parameters.Add(new SqlParameter(“ServiceCode”, SqlDbType.VarChar, 10));
    mydataadapter.SelectCommand.Parameters[“ServiceCode”].Value = ds.Tables[0].Rows[0].ToString();
    mydataadapter.Fill(ds, “ServiceCode”);
    TextBox sc = GridView1.Controls[0].Controls[0].FindControl(“TxtServiceCode”) as TextBox;
    //sc.Text = mydataadapter[“ServiceCode”].Tostring();

  25. really greate

  26. What if i only want to add only that record to the gridvew which i have just inserted in the database.

    Thanks in advance and regards

  27. ya its good solution.Thank u

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s