DotNet Friends

April 18, 2008

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://amitpatriwala.blogspot.com/

13 Comments »

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

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

    Comment by Sriram — July 22, 2008 @ 4:47 pm

  2. Thanks For Your Motivational Comment.

    Have a gr8 day ahead.

    Comment by patriwala — July 23, 2008 @ 4:52 am

  3. pls sent me its update row code

    Comment by renu — July 24, 2008 @ 6:00 pm

  4. Renu,

    sure i will post an article very soon.

    Comment by patriwala — July 25, 2008 @ 4:59 am

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

    Comment by ANWER JAMAL — February 21, 2009 @ 6:41 am

  6. Thanx nice article.

    Comment by SUJIT MANDAL — February 24, 2009 @ 12:59 pm

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

    Thanks..

    Comment by santosh — March 2, 2009 @ 8:36 am

  8. It is an very very nice one thanx for this

    Comment by santhosh — March 17, 2009 @ 9:10 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

    Comment by manisha — June 10, 2009 @ 7:02 am

    • nice thought…

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

      Comment by ashish — June 27, 2009 @ 2:43 pm

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

        Comment by Kevin — July 17, 2009 @ 3:20 pm

  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.

    Comment by Kevin — July 17, 2009 @ 5:23 pm

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

    Comment by Andy — October 2, 2009 @ 8:57 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.