Home > Asp.Net 2.0 > Inserting New Row in GridView in Asp.net 2.0

Inserting New Row in GridView in Asp.net 2.0

steps:

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

addnewrow

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">
                <Columns>
                    <asp:TemplateField HeaderText="UserID" InsertVisible="False" SortExpression="UserID">
                        <ItemTemplate>
                            <asp:Label ID="lblUserID" runat="server" Text='<%# Eval("UserID") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="UserName" SortExpression="UserName">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtUserName" runat="server" Text='<%# Bind("UserName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblUserName" runat="server" Text='<%# Eval("UserName") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                        <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>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Address1" SortExpression="Address1">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtAddress1" runat="server" Text='<%# Bind("Address1") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblAddress1" runat="server" Text='<%# Eval("Address1") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                        <asp:TextBox ID="txtfooterAddress1" runat="server"></asp:TextBox>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="EmailAddress" SortExpression="EmailAddress">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtAddress1" runat="server" Text='<%# Bind("EmailAddress") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblEmailAddress" runat="server" Text='<%# Eval("EmailAddress") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                        <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>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="EditRecord">
                        <EditItemTemplate>
                            <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                                Text="Update"></asp:LinkButton>
                            <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                                Text="Cancel"></asp:LinkButton>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                                Text="Edit"></asp:LinkButton>
                        </ItemTemplate>
                        <FooterTemplate>
                        <asp:LinkButton ID="lnkInsert" runat="server" Text ="Insert" OnClick="lnkInsert_Click"></asp:LinkButton>
                        </FooterTemplate>
                    </asp:TemplateField>
                </Columns>
                <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:GridView>
<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
            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
        adp.Fill(ds);

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

        GridView1.DataBind();
    }

   

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
        sqlcon.Open();
        // Execute the Insert Command In to Database
        sqlcmd.ExecuteNonQuery();
        //close the sqlconnection
        sqlcon.Close();
        //if record successfully insert we display the message
        lblMessage.Visible = true;
        //bind grid view for latest record
        BindGridView();
    }

Check Application.

Thanks.

http://www.ibusiness-management.com/

  1. Sriram
    July 22, 2008 at 4:47 pm | #1

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

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

  2. July 23, 2008 at 4:52 am | #2

    Thanks For Your Motivational Comment.

    Have a gr8 day ahead.

  3. renu
    July 24, 2008 at 6:00 pm | #3

    pls sent me its update row code

  4. July 25, 2008 at 4:59 am | #4

    Renu,

    sure i will post an article very soon.

  5. ANWER JAMAL
    February 21, 2009 at 6:41 am | #5

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

  6. SUJIT MANDAL
    February 24, 2009 at 12:59 pm | #6

    Thanx nice article.

  7. santosh
    March 2, 2009 at 8:36 am | #7

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

    Thanks..

  8. santhosh
    March 17, 2009 at 9:10 am | #8

    It is an very very nice one thanx for this

  9. manisha
    June 10, 2009 at 7:02 am | #9

    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

    • June 27, 2009 at 2:43 pm | #10

      nice thought…

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

      • Kevin
        July 17, 2009 at 3:20 pm | #11

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

      • Monsignor
        August 3, 2010 at 4:00 am | #12

        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;
        gvJobTitles.DataBind();

        // 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;
        }
        }

      • Vladislav M
        September 5, 2010 at 10:53 am | #13

        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. Kevin
    July 17, 2009 at 5:23 pm | #14

    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. October 2, 2009 at 8:57 am | #15

    Hey thanks a ton..it helped me a lot..
    thanku veryyyyyyyyyyyyyy much

  12. March 23, 2010 at 10:14 am | #16

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

  13. Vanchinathan
    April 1, 2010 at 8:11 am | #17

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

  14. Vamsi
    April 21, 2010 at 6:01 am | #18

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

  15. anto
    April 28, 2010 at 10:19 am | #19

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

  16. kalpana
    June 17, 2010 at 10:25 am | #20

    Thank u soooooooooo much……

  17. yousof
    September 29, 2010 at 6:48 am | #21

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

  18. saikanth
    December 20, 2010 at 4:44 pm | #22

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

  19. saikanth
    December 22, 2010 at 5:26 pm | #23

    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
    April 25, 2011 at 1:17 pm | #24

    Really greate

  21. José
    June 4, 2011 at 8:56 pm | #25

    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.

    Preguntas:

    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).

    dimurve@hotmail.com

  22. José
    June 6, 2011 at 7:29 pm | #27

    Saludos.

    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
    June 13, 2011 at 12:00 pm | #28

    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.
    Regards

    • Gaurav Singh
      September 23, 2011 at 4:58 am | #29

      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. sai
    October 26, 2011 at 1:17 pm | #30

    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”>

    TxtServiceCode

    <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();
    mydataadapter.Dispose();
    MyConnection.Close();

  25. ganesh
    November 10, 2011 at 6:33 am | #31

    really greate

  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

Join 244 other followers