|
|
Adding a New Row in GridView
AzamSharp
Published Date: 8/15/2005 8:15:42 PM
Views: 82610
Abstract:
Every application has some sort of form to enter the information. The add form can be a separate page or the same page separated by panels. In this article we will see how we can add a new row in the GridView control by using the GridView footer template.
Introduction
Every application has some sort of form to enter the information. The add form can be a separate page or the same page separated by panels. In this article we will see how we can add a new row in the GridView control by using the GridView footer template.
Creating the User Interface:
The User Interface is pretty simple. All you have to do is assign a DataSource to the GridView control. In this case my DataSource is a DataSet which is filled using SqlDataAdapter.
Here is a screen shot of a TextBox added to the footer of the GridView control.

Here is the HTML Source of the GridView control in which you can see that the TextBox is being added in the footer template of the GridView Control. The Button control CommandName property has been given the name "ADD" so that we can catch the event generated in the GridView item events.
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" AllowSorting="True" AutoGenerateColumns="False" ShowFooter="True" OnRowCommand="GridView1_RowCommand"> <FooterStyle BackColor="#99CCCC" ForeColor="#003399" /> <RowStyle BackColor="White" ForeColor="#003399" /> <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" /> <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" /> <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" /> <Columns> <asp:BoundField DataField="PersonID" HeaderText="PersonID" /> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <asp:Label ID="Label1" Text='<%# Eval("Name") %>' runat="server"></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtName" runat="server"></asp:TextBox> <asp:Button ID="Button1" CommandName = "ADD" runat="server" Text="Add" /> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView> |
BindData Method:
Let's see the code for the BindData method which is called when there is no postback. The primary purpose of this method is to populate the GridView control.
| private void BindData()
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM tblPerson", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "tblPerson");
GridView1.DataSource = ds;
GridView1.DataBind();
}
|
Catching the Event Generated by Button Click in the Footer:
As you have already noticed that there is also a Button control inside the Footer of the GridView control. We can easily catch the events and access the TextBox which resides in the Footer.
GridView RowCommand event is generated when ever any event occurs inside the GridView control. This is the best place to catch the Button click event.
| protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
// We are checking against the "ADD"
if (e.CommandName == "ADD")
{
string name = ((TextBox) GridView1.FooterRow.FindControl("txtName")).Text;
AddNewRecord(name);
}
} |
Now that we have got the text in the string variable we are ready to insert the new data. The new data is inserted by a small method named AddNewRecord(string name).
| private void AddNewRecord(string name)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
string query = @"INSERT INTO tblPerson(Name) VALUES(@Name)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@Name", name);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
BindData();
}
|
I hope you liked the article, happy coding!
Comments/Feedbacks
|
|
|
|
Subject: Doesn't work if no data is returned
Name: Vinh
Date: 2/3/2007 9:54:31 AM
Comment: Hi there.
Thanks for the tutorial. I noticed that when no data is returned...user is unable to add to the list items. Do u have a solution for this? Thanks@! |
|
|
|
|
|
Subject: Solution
Name: AzamSharp
Date: 2/3/2007 10:46:21 AM
Comment: When no rows are returned then you can use the EmptyDataTemplate of the GridView control. The EmptyDataTemplate will be visible when there are no rows to bind to the GridView control. |
|
|
|
|
|
Subject: Doesn't work for me.
Name: abichap
Date: 2/6/2007 5:39:43 AM
Comment: Hi AzamSharp,
I followed your gridview tutorials and they were great. However i can't seem to get this article working. I am not why. I copied all your code and when I viewed it in web browser, I do not get anything at all. Strange isn't it? |
|
|
|
|
|
Subject: VB Script code
Name: Soraya Chetty
Date: 2/28/2007 6:43:25 AM
Comment: Hi,
Do you have the VB script version of this code ?? If so will you please mail it to me ??
Thanks |
|
|
|
|
|
Subject: insert a new row in grid
Name: sanjeev
Date: 3/28/2007 2:22:26 PM
Comment: hi,
it is good but if we have to add a new row in between in gridview.
then what we will have to do? |
|
|
|
|
|
Subject: Great example
Name: pwb
Date: 5/9/2007 10:42:47 AM
Comment: Greetings -
I used the FooterTemplate concept you described and applied it several of my gridview controls in a recent application. Works great. Made my life much easier! The GridView control gets more flexible each time I implement it. |
|
|
|
|
|
Subject: footer template
Name: dhanaraj
Date: 5/25/2007 4:33:42 AM
Comment: thank you tutorial |
|
|
|
|
|
Subject: Textbox in Gridview
Name: Paul Minnaar
Date: 6/12/2007 7:51:43 AM
Comment: Hi AzamSharp
I have read most of your articles RE gridviews and the additional controls you can add to them. I have now added a textbox to the gridview, but i am unsure how to access the text in the textbox. I can place the text in an array, but to retrieve it again poses some difficulty it seems. Could you perhaps help?
Regards
Paul |
|
|
|
|
|
Subject: RowCommand event doesn't fire when Add button is pressed from the Footer
Name: Konstantin
Date: 6/20/2007 9:43:19 AM
Comment: Hi,
I have a templated grid with columns being generated dynamically, because it is unknows what the field in the datasource are. So, I use ITemplate to create my Columns. In the footer I create a button "Insert" and set CommandName property to "Insert". However, I cannot catch this command in GridView1_RowCommand event, because it never actually goes there. Any help is greatly appreciated. Thanks |
|
|
|
|
|
Subject: gridview footertemplate
Name: navdeep
Date: 6/20/2007 11:44:13 PM
Comment: gud one |
|
|
|
|
|
Subject: gridview
Name: saroja
Date: 6/27/2007 2:10:56 AM
Comment: nice one!!!!! |
|
|
|
|
|
Subject: It's fine, but...
Name: Venkataramana.K
Date: 7/11/2007 3:50:33 AM
Comment: I want to add the footer templates dynamically. the templates should contain the textboxes. Can u please help me..... |
|
|
|
|
|
Subject: I have one error in runtime
Name: Laxmikanth
Date: 9/5/2007 11:22:17 PM
Comment: Code is good, But i have one runtime error in this program Plz Help me yare
When i press the add button it goes an error...
I.e.,
Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
|
|
|
|
|
|
Subject: RE: I have one error in runtime
Name: AzamSharp
Date: 9/9/2007 9:19:37 AM
Comment: Hi Laxmikanth,
Please post the code where you are getting the error.
|
|
|
|
|
|
Subject: Excelent Code
Name: Vinay Mistry
Date: 9/11/2007 9:58:13 PM
Comment: Thats a very good Code..... |
|
|
|
|
|
Subject: Insert Record
Name: Pushkar
Date: 10/12/2007 7:14:35 AM
Comment: Hii Guys...
Its great site for the Gridview solution..
I have used almost all the examples that you have given...
Please keep continue posting new articles... |
|
|
|
|
|
Subject: Doesn't work
Name: Yasser Zaid
Date: 11/14/2007 6:42:15 AM
Comment: Doesn't work |
|
|
|
|
|
Subject: RE: Does not work
Name: AzamSharp
Date: 11/14/2007 6:59:20 AM
Comment: Hi Yasser Zaid,
That was not so much informative comment. What does not work? What problems are you facing? |
|
|
|
|
|
Subject: Very useful.
Name: Mahesh
Date: 12/19/2007 6:46:39 AM
Comment: Hi Azam, I call your site as one stop solution for all gridview problem and queries. VERY USEFUL for me to do POC on time. Thanks a lot !! god bless you. |
|
|
|
|
|
Subject: no data, add new
Name: cs
Date: 1/9/2008 8:43:22 AM
Comment: hi AzamSharp , when there is no data and I want to show the footer template with 'Add New' button, how do I do that?
Thanks for this useful article! |
|
|
|
|
|
Subject: asp.net, isqlanywhere
Name: hello
Date: 1/31/2008 2:08:39 AM
Comment: hi all,
thanks it is vety helpfull for me
its really very nice. sort and sweet code |
|
|
|
|
|
Subject: RE: I have one error in runtime
Name: sid
Date: 2/7/2008 8:11:39 AM
Comment: On your source code, set the EnablePageValidation="false" |
|
|
|
|
|
Subject: nice
Name: NTS
Date: 2/13/2008 11:33:46 PM
Comment: it is very helpful |
|
|
|
|
|
Subject: Add New Row To Gridview On ButtonClick
Name: KashifBari
Date: 2/18/2008 6:57:42 AM
Comment: Hello there i have a problem i want to add a blank row with textboxes to girdview to insert new record on ButtonClick.Let me tell you i dont want the new row to be added in Footer i just want as many times user Click the AddRow Button new row should be appeared in Gridview. |
|
|
|
|
|
Subject: RE: Add New Row
Name: AzamSharp
Date: 2/18/2008 10:16:38 AM
Comment: http://www.gridviewguy.com/ArticleDetails.aspx?articleID=374_Adding_Multiple_Rows_in_the_GridView_Control |
|
|
|
|
|
Subject: Error
Name: ravi
Date: 2/22/2008 6:37:05 AM
Comment: the fowllowing Error is displayed when use above code
Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
|
|
|
|
|
|
Subject: does not work
Name: stan
Date: 2/22/2008 12:51:46 PM
Comment: Hi,
thanks for the article but my problem is that i used your example but on postback i loose whatever i had typed in the textbox. the textbox is on grid footer.
any help will be appreciated.
below is a snapshot:
|
|
|
|
|
|
Subject: EXECELENT
Name: ING.JOSE ARTURO PITTI
Date: 3/9/2008 2:25:21 PM
Comment: Thanks a lot. very good code |
|
|
|
|
|
Subject: RE: not working
Name: AzamSharp
Date: 3/10/2008 2:26:58 PM
Comment: Hi Stan,
Make sure that you are binding only when there is no postback.
In the page load do something like this:
if(!Page.IsPostBack)
{
BindData();
}
|
|
|
|
|
|
Subject: grid-checkbox problem
Name: aaryan
Date: 3/25/2008 3:10:41 AM
Comment: Hi,can any one help me by telling how i can delete rows from a grid which r selected by checkbox column of the grid.The data source of d grid is provided through table adapter.
Plz help........ |
|
|
|
|
|
Subject: It's work's fine
Name: Marques
Date: 3/25/2008 11:25:37 PM
Comment: Very good article. Is worked fine and it's very useful. |
|
|
|
|
|
Subject: Reg: Adding rows
Name: Anil Abraham
Date: 4/4/2008 5:30:27 AM
Comment: Hi
I used the code as in ur post, I added a button on the footer of my gridview. When am pressing the button am getting eventvalidation error,when i make the page.eventvalidation =false,the error is not hapening ,but the data is not getting stored into the Database.
Kindly share ur idea |
|
|
|
|
|
Subject: Empty Row
Name: Agnes Loyola
Date: 4/14/2008 5:09:20 AM
Comment: i have set the Empty data Text as NO RECORDS FOUND for the Gridview. when there was no records in the table , i got the result as NO RECORDS FOUND for the Gridview. And I am not able to insert any new data because the Footer is not visible.What I want is the Gridview should show the footer in order to enter new data.I used the same coding as given in this article. |
|
|
|
|
|
Subject: Hi LakxmiKanth and ravi
Name: Agnes Loyola
Date: 4/14/2008 5:17:12 AM
Comment: Hope u both have the same error. Add this tag pages enableEventValidation="false" between the opening and closing tag of system.web in the web.configuration file.
|
|
|
|
|
|
Subject: Bringing text to Next Line
Name: Agnes Loyola
Date: 4/15/2008 2:48:14 AM
Comment: I have added the data AS,SD,FG,AW,DF,ER,RT,MN,KL,HJ,DF,RT,TY,AW,QW,TY,Yu,IO,PL in a cell through the footer and it also added in the Table as a single line. When viewing the Gridview I am not able to see the full line (but the data is there).I wants this single line to be display in two lines. Can any one help me? Its urgent. |
|
|
|
|
|
Subject: What if Dropdownlist
Name: Suresh
Date: 5/5/2008 11:26:35 PM
Comment: Hi,
I am using a same concept but I have a dropdownlist. When we clik on add the dropdownlist should be filled with data and then displayed. What is the solution. |
|
|
|
|
|
Subject: It is very nice
Name: Haribabu chowdary
Date: 5/21/2008 10:03:21 PM
Comment: Your code is very good. |
|
|
|
|
|
Subject: Insert a new row in grid
Name: Haribabu chowdary
Date: 5/23/2008 1:24:21 AM
Comment: It is very helpfull |
|
|
|
|
|
Subject: Error
Name: Gary
Date: 6/28/2008 11:52:14 AM
Comment: Hi,
I like the concewpt, however, I get an error using it.
Parser ErrorMessage: System.Web.UI.WebControls.DataControlFieldCollection must have items of type 'System.Web.UI.WebControls.DataControlField'. 'FooterTemplate' is of type 'System.Web.UI.HtmlControls.HtmlGenericControl'.
Does this work in ASP.net 2.0? |
|
|
|
|
|
Subject: topic comment
Name: Imran
Date: 6/30/2008 12:07:42 AM
Comment: Its very beginner level article that you have written. |
|
|
|
|
|
Subject: GridView
Name: Pravin
Date: 8/21/2008 1:10:00 AM
Comment: I don't want this code. I want - how to add multiple rows in the grid and save all at a time. Can you help me. Plese! |
|
|
|
|
|
Subject: RE: GridView
Name: AzamSharp
Date: 8/25/2008 7:59:39 PM
Comment: Hi Pravin,
You can check out the following article:
http://www.gridviewguy.com/ArticleDetails.aspx?articleID=374_Adding_Multiple_Rows_in_the_GridView_Control
|
|
|
|
|
|
Subject: Best Regards,
Name: Muhammad Imran Khan
Date: 10/8/2008 10:07:14 PM
Comment: This article has solved a very big problem for me |
|
|
|
|
|
Subject: GridviewRow
Name: Jayakumar
Date: 12/23/2008 1:49:44 AM
Comment: Scenario : In a GridView each row contains some editable controls and the 'Copy', 'Save' button, if user wants one of the row duplicated and save with different values, he can click on Copy, the Copy will make that row duplicated in the dataset and rebind to Grid.
Now user is changed the values of the editable control and click on Save. The error occured as 'Index was out of range. Must be non-negative and less than the size of the collection.' It is for sure the newly created row is not added to the Gridviewrow collection, this is just shallow copy.
can you please suggest me how can i make sure the newly created row is added to the Gridviewrow collection?
Thank you in advance
Kumar |
|
|
|
|
|
Subject: Does not work for me
Name: sd
Date: 1/24/2010 1:35:52 AM
Comment: Hi AzamSharp, I followed your gridview tutorials and they were great. However i can't seem to get this article working. I am not why. I copied all your code and when I viewed it in web browser, I do not get anything at all. |
|
|
|
|
|
Subject: Gridview Insert
Name: sibadata
Date: 2/15/2010 3:20:07 AM
Comment: Thank u for your Coding. It help me lot.
Can Explain how insert record in gridview bu using EmptyTemplate and that should come in the top of grid view instead of footer. |
|
|
|