|
|
GridView All Rows in Edit Mode
AzamSharp
Published Date: 11/25/2006 9:58:15 AM
Views: 60696
Abstract:
GridView provides a very easy way to edit the data by using the in-place editing feature. Although the feature is great but sometimes we want to view the complete GridView in the edit mode and quickly edit multiple records without having to click the edit button on each row. In this article I will demonstrate how to convert the whole GridView in edit mode with a click of a button.
Introduction:
GridView provides a very easy way to edit the data by using the in-place editing feature. Although the feature is great but sometimes we want to view the complete GridView in the edit mode and quickly edit multiple records without having to click the edit button on each row. In this article I will demonstrate how to convert the whole GridView in edit mode with a click of a button.
Database Design:
In this article I will be using a custom database called School which consists of a single table called “Users”. The Users table contains only three columns namely FirstName, LastName and UserID.
Displaying Data in the GridView Control:
The first task is to display the data in the GridView control. Take a look at the method below which is used to populate the GridView control.
private void BindData()
{
string connectionString = "Server=localhost;Database=School;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT UserID, FirstName, LastName FROM Users", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds); gvUsers.DataSource = ds; gvUsers.DataBind();
}
Depending on the data in the database your GridView will be populated.

GridView HTML Code:
The HTML code of the GridView is where all the magic happens. Let’s first take a look at the code.
<asp:GridView ID="gvUsers" AutoGenerateColumns="False" runat="server" OnRowDataBound="gvUsers_RowDataBound" CellPadding="4" Font-Names="Verdana" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="User ID">
<ItemTemplate>
<asp:Label ID="lblUserID" runat="server" Text='<%# Eval("UserID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("FirstName") %>' />
<asp:TextBox ID="txtFirstName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("FirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("LastName") %>' />
<asp:TextBox ID="txtLastName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("LastName") %>' />
</ItemTemplate>
</asp:TemplateField> </Columns>
</asp:GridView>
Now, check out the <Columns> section where all the TemplateFields exists. The <ItemTemplate> section contains the Label as well as the TextBox. The visibility of the Label and the TextBox depends on the IsInEditMode property which, is a public property defined in the code behind. You can think of it as a switch meaning that when the Labels are displayed then the TextBoxes are not displayed and when the TextBoxes are displayed then the Labels will not be displayed.
IsInEditMode Property:
This is a simple property that returns the Boolean value of true or false.
private bool isEditMode = false;
protected bool IsInEditMode
{
get { return this.isEditMode; }
set { this.isEditMode = value; }
}
I have used a simple ASP.NET Button control to change the GridView to edit mode. Check out the code below:
// This method will put the GridView in the edit mode
protected void Button1_Click(object sender, EventArgs e)
{
isEditMode = true;
BindData();
}
Yup! That is all you need to change the GridView to edit mode. The isEditMode variable is set to true and it will make TextBoxes visible and the Labels invisible.

The screenshot above shows the GridView in edit mode. In order to switch back to view mode all you need to do is to change the IsInEditMode to false and call the BindData method.
Hope you liked the article, happy coding!
Comments/Feedbacks
|
|
|
|
Subject: GridView All Rows in Edit Mode
Name: Riz
Date: 3/7/2007 1:06:44 AM
Comment: Hey Azam,
Great examples you have, thanks, very helpful.
After making edits and switching back to view mode, does this automatically cause the data to be updated in the database?
Thanks.
Riz |
|
|
|
|
|
Subject: RE: GridView All Rows in Edit Mode
Name: AzamSharp
Date: 3/12/2007 8:49:49 PM
Comment: Hi Riz,
You will need to run a stored procedure or a query to actually perform the update.
Check out my blog post:
http://aspadvice.com/blogs/azamsharp/archive/2006/12/18/GridView-Update-All-Rows-At-Once.aspx
|
|
|
|
|
|
Subject: Good One
Name: NIshant
Date: 3/28/2007 8:18:58 AM
Comment: THis is a very good article but i appriciate you if you do Selecting row update in the GridView withpout any source control.Thankx in advance. |
|
|
|
|
|
Subject: RE: Good One
Name: AzamSharp
Date: 4/12/2007 1:20:20 PM
Comment: Hi Nishant,
Check out the blog post in the thread above. |
|
|
|
|
|
Subject: good work..
Name: Dheeraj
Date: 4/26/2007 8:47:58 AM
Comment: thnks azam
i want to say that a lot of website directly give code which doen not help much,except for that specific project or requirement.
but reading through you article gives logic and basic approach which helps to build the base stronger.Every tree has one root despite it can have many branches. |
|
|
|
|
|
Subject: need help
Name: Dheeraj
Date: 5/8/2007 9:02:31 AM
Comment: hey azam
i need to edit and update each gridview row by row programmatically.how to do it?i dont want to use sql data source.
plz help..
i m novice in coding |
|
|
|
|
|
Subject: So Cool
Name: Charlie Seitz
Date: 5/25/2007 9:17:10 AM
Comment: Thank you for your awesome examples. I will choose a GridView over a DataGrid any day of the week. |
|
|
|
|
|
Subject: Multiple Editing in GridView Control.
Name: GCI Solutions
Date: 6/22/2007 4:01:46 AM
Comment: Hi,
Thanks for the tip. It is really a good logic to implement Multi editing in GridView Control. |
|
|
|
|
|
Subject: Different data-binding method that example
Name: Mark
Date: 7/13/2007 7:19:33 AM
Comment: Hi, Azam,
Great article! As is, I understand how it works, but in my limited experience, I'm not sure how to implement your method in my own situation.
I'm using the DataSourceID property of my GridView to bind the grid with an ObjectDataSource. The GridView isn't bound from the aspx's code-behind, it's done via a set of business layer classes that, frankly, I barely understand enough to put my page together!
One thing I do know is that the ObjectCreating event is called for each of the objectdatasources on the aspx page. The code in that sub is: e.ObjectInstance = New PersonnelSystem(m_sDBInstance)
I'm not sure you can help me with that info, but could you maybe point me in the right direction?
Thanks!
Mark |
|
|
|
|
|
Subject: RE: Different data-binding method that example
Name: AzamSharp
Date: 7/13/2007 4:53:04 PM
Comment: Hi Mark,
I am pretty sure that you can use an DataSource for this example. The main work is done by the IsEditMode property which toggles between the Labels and the TextBoxes. The IsEditMode binding expression is fired when the GridView is binded on the page.
GridView1.DataBind() will call the IsEditMode property to be fired! |
|
|
|
|
|
Subject: A problem
Name: Shahid Afzal
Date: 7/26/2007 12:46:11 AM
Comment: Good article. I found it very useful. I have got one problem with it. I don't know am I doing something wrong. I build a gridview using this article. When I clck edit button grid comes into editable mode. I edit my desired data. I also put a Update button on my page. On that button I am reading the data from grid and saving it in my database. But when I read data from text boxes in grid it reads the old data not the modified valuse. I am using the following code to read data from grid and put it into a string.
StringBuilder sb = new StringBuilder();
sb.Append("Update tblDepartment set DepartmentName= '");
sb.Append((grvrow.FindControl("txtDeptName") as TextBox).Text);
sb.Append("' ,");
sb.Append("DepartmentType = '");
sb.Append((grvrow.FindControl("txtDeptType") as TextBox).Text);
sb.Append("' ");
sb.Append("Where Deptid= '");
sb.Append(Convert.ToInt32((grvrow.FindControl("lblDeptID") as Label).Text));
sb.Append("'");
Can you tell me why its reading old values not updated values from grid? |
|
|
|
|
|
Subject: RE: A problem
Name: AzamSharp
Date: 7/26/2007 2:45:50 PM
Comment: Hi Shahid Afzal,
Your code seems fine. Make sure you are populating the Grid only when there is no postback inside the Page_Load event.
|
|
|
|
|
|
Subject: Congrats.....
Name: Sumeet Kawali
Date: 8/30/2007 6:22:36 AM
Comment: excellent customizationg of grid view....do keep posting such articles. |
|
|
|
|
|
Subject: RE: Congrats
Name: AzamSharp
Date: 9/1/2007 11:24:17 AM
Comment: Hi Sumeet Kawali,
I am glad you liked the article. |
|
|
|
|
|
Subject: Row affected
Name: James
Date: 9/12/2007 10:28:23 AM
Comment: Hi Azam,
I've been looking for simple solution for editing a Gridview without buttons for the last three days and finally found it here. Your article fits my need perfectly. Thanks a lot for writing this.
However, I need to know what row affected when a dropdownlist's value in my Gridview is changed. I could not figure out how to get the index row of my dropdownlist so I can manipulate data in other column, plus my Gridview1_SelectedIndexChanged never get fired (so I would know what row affected)
Any suggestions are appreciated,
James |
|
|
|
|
|
Subject: RE: Rows Affected
Name: AzamSharp
Date: 9/13/2007 4:18:06 AM
Comment: Hi James,
You can get the RowIndex of the row which generated the DropDownList event by the use of the SelectionChanged event of the DropDownList. You will need to write code like the following:
DropDownList_SelectionChanged
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow) ddl.NamingContainer;
After that you can do row.RowIndex to get the index of the row which generated the event.
|
|
|
|
|
|
Subject: Thank you so much for a simple solution
Name: James
Date: 9/13/2007 7:22:37 AM
Comment: Hi Azam,
Thanks a lot for answering my question. It works great. I really appreciate it and wish you will write more articles. Looking forward to read it.
James |
|
|
|
|
|
Subject: RE: Thank you so much for a simple solution
Name: AzamSharp
Date: 9/14/2007 2:09:07 PM
Comment: Hi James,
I am glad that I was able to help. |
|
|
|
|
|
Subject: RE: Rows Affected
Name: Natraj
Date: 9/27/2007 3:40:04 AM
Comment: Hi AzamSharp ,
You code to find the row affected is work fine.But the problem is if I select a value from 1st row.And again try to select a value in 5th row.but that method only return the 1st row value.
Please help on this. |
|
|
|
|
|
Subject: Question about an earlier question
Name: Craig
Date: 10/18/2007 9:21:18 AM
Comment: Hi Azam,
I'm not sure I understand your response to James's question of 9/12/2007. I have a DropDownList in my grid also, but I don't see how to create an event for it. The DropDownList does not show up in the list of controls on my webform.
Thanks!
Craig |
|
|
|
|
|
Subject: All rows editable
Name: rob
Date: 11/10/2007 2:46:03 PM
Comment: Hi Azam - I thought your technique of using both labels and textboxes in the same template column was quite smart and I have used this technique in the edit template cols of a gridview to implement business rules. I set cols as readonly or editable in the row being edited depending upon data conditions by show/hide of the label or textbox in the rowdatabound event. It all works swimmingly until I try to edit the selected row and then the edit event doesn't occur in row databound. Can you think of resolution for this? |
|
|
|
|
|
Subject: all rows in edit mode
Name: rob
Date: 11/11/2007 1:01:40 AM
Comment: Hi Azam - re edit mode not registering in gridview rowdatabound event. I have found a workaround - when you click edit the update and cancel link buttons become visible so in rowdatabound i look for the update button and if i find it i deduce that the row is in edit mode. Bit clunky but it works when the row being edited is also selected and that was my problem. Not a perfect solution though because if the name of the link button is ever changed to 'save' or 'ok' for example my code stops working. |
|
|
|
|
|
Subject: GridView All Rows Edit
Name: Mick
Date: 11/13/2007 9:36:21 AM
Comment: Thanks Azam,
Excellent example and a answer to this question will give me exactly what I need.
I want to use a "parameter" in my SQL statement. I can not seem to find a example of how to use a "command parameter" to insert a tex box vakue into my SQL statement using the DataAdapter????
Thanks again Mick |
|
|
|
|
|
Subject: RE: GridView All Rows Edit
Name: AzamSharp
Date: 11/13/2007 1:03:09 PM
Comment: Hi Mick,
In order to update all the rows you will need to generate a parameterized string. Something like this.
string query = "INSERT INTO Customers(FirstName,LastName)VALUES(@FirstName,@LastName)
Now, in the C# code you will add the parameters using the SqlCommand object.
SqlCommand myCommand = new SqlCommand(query,myConnection);
myCommand.AddParameter("@FirstName",[value from the first name textbox]);
And so on! You will need to do this in a loop! |
|
|
|
|
|
Subject: RE: Question about earlier question!
Name: AzamSharp
Date: 11/13/2007 1:07:14 PM
Comment: Hi Craig,
You will not see the DropDownList inside the forms and that is because it is contained inside the GridView control. You can go to the ItemTemplate or EditItemTemplate and then you will see the DropDownList. From there you can attach the events to the DropDownList. After that you can follow the same approach as I posted above for James. |
|
|
|
|
|
Subject: PERFECT!
Name: Irina
Date: 11/14/2007 9:56:49 AM
Comment: FANTASTIC post - thanks SO much!! I've looked all over the web for a simple way to do this and yours is the best post around! |
|
|
|
|
|
Subject: RE: Perfect
Name: AzamSharp
Date: 11/14/2007 11:12:38 AM
Comment: Hi Irina,
I am glad that you liked the article. I have created a new website which is the recommended website for all the articles. It is www.koffeekoder.com. I am sure you will enjoy the website. |
|
|
|
|
|
Subject: this code is working
Name: benitto
Date: 3/4/2008 11:44:28 PM
Comment: All fields are appear in edit mode
and how update this? |
|
|
|
|
|
Subject: good code
Name: beni
Date: 3/5/2008 12:01:01 AM
Comment: please send update code |
|
|
|
|
|
Subject: good
Name: babu
Date: 3/13/2008 3:10:29 AM
Comment: simple logic |
|
|
|
|
|
Subject: gridview
Name: praveen
Date: 3/18/2008 11:55:59 PM
Comment: it is fine |
|
|
|
|
|
Subject: Grid View Edit Row
Name: Shaik Mujahid
Date: 3/28/2008 12:08:39 AM
Comment: I am using retriving the data from a database and displaying in grid view i wanted to work with template field methord and manually place a control and get a result of editing adding and deleting every thing in gridview but iam not well at gridview command of coding please give me an example please |
|
|
|
|
|
Subject: hi
Name: joydeb
Date: 4/29/2008 6:59:34 AM
Comment: hi,azam
i have got 1 problem.when i am trying out ur code with itemtemplate i am getting that first name and last name as extra heading.means four times i am getting the heading.two from data base and and another two from template header text.i need urgent solution.plz help me out. |
|
|
|
|
|
Subject: RE: Hi
Name: AzamSharp
Date: 4/30/2008 9:16:13 AM
Comment: Hi Joydeb,
Make sure you are using one label and one textbox inside the itemtemplate field. If you use two labels then you will get two headings.
Not sure if that answers your question! |
|
|
|
|
|
Subject: Nice
Name: Kamran Shahid
Date: 5/20/2008 4:43:19 AM
Comment: Wow.
Very simple and nice solution |
|
|
|
|
|
Subject: grid view in editmode
Name: malik
Date: 6/19/2008 9:58:30 PM
Comment: hi,
how to get the gridview row in edit mode while clicking edit button on that row |
|
|
|
|
|
Subject: VB conversion
Name: KP
Date: 7/9/2008 6:54:35 AM
Comment: Good stuff. I've converted all to VB.NET for my app, but stuck on converting this line: Visible='<%# !(bool) IsInEditMode %>' to VB.NET. Anyone know? |
|
|
|
|
|
Subject: HI KP
Name: vijay
Date: 7/17/2008 4:24:46 AM
Comment: u can directly use the propert in vb.net like this :-
Visible='<%# IsInEditMode %>' |
|
|
|
|
|
Subject: RowDataboubd code
Name: Joe
Date: 8/18/2008 8:47:37 AM
Comment: How is the gridview.rowdatabound coded? |
|
|
|
|
|
Subject: RE: RowDataboubd code
Name: AzamSharp
Date: 8/20/2008 1:06:51 PM
Comment: Hi Joe,
There is no code in the RowDataBound event. When the GridView.DataBind() is called it evaluates the IsEditable expression which makes the GridView editable. |
|
|
|
|
|
Subject: It Gives "Parse Error"
Name: Shahid Khan
Date: 9/24/2008 1:32:09 AM
Comment: Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: System.Web.UI.WebControls.DataControlFieldCollection must have items of type 'System.Web.UI.WebControls.DataControlField'. 'ItemTemplate' is of type 'System.Web.UI.HtmlControls.HtmlGenericControl'.
Source Error:
Line 164:
Line 165:
Line 166:
Line 167:
Line 168:
Source File: /lims/ToDoList.aspx Line: 166 |
|
|
|
|
|
Subject: GridView EditMode Issue
Name: Andrew Grigg
Date: 11/24/2008 1:48:02 PM
Comment: Hey Azam,
I have an issue where I am using the standard method to enable single line editing.
[1] Clicking the edit link resulted in nothing happening.
[2] I set the GridView.EditIndex in the GridView_RowEditing event, but the edit controls don't appear until either a second click on the edit link OR doing anything that causes a postback to occur.
Do you have any ideas on how I can get around this ?
Thanks, Andrew |
|
|
|
|
|
Subject: GridView All Rows in Edit Mode
Name: Rajesh
Date: 3/17/2009 6:16:23 AM
Comment: You may also find an alternate way recommended by Microsoft,
http://msdn.microsoft.com/en-us/library/aa992036.aspx |
|
|
|
|
|
Subject: Great article!!
Name: Afroditi
Date: 3/30/2009 7:34:46 AM
Comment: Hi there...your example was great!!thanks a lot!I'm new in asp.net and vb..So...I want to get the cell value from editable cell.I use GridView.Rows(i).Cells(j).Text but returns " ".I get value only for readonly columns.Any suggestions?? |
|
|
|
|
|
Subject: how to update
Name: pramod
Date: 3/31/2009 2:54:34 AM
Comment: It's better if u provide code to update the whole gridview at a time |
|
|
|
|
|
Subject: Great article!!
Name: Afroditi
Date: 3/31/2009 7:02:45 AM
Comment: Hi...again!I found the way to get value from editable cell: CType(GridView.Rows(i).FindControl("ID"), TextBox).
You have to convert the fields into TemplateFields first.
Now...i need help to read the value after user change this. CType(GridView.Rows(i).FindControl("ID"), TextBox) gives the initial value from the datasource.
What I mean is that when I load the page the value, for example is 5. I change it to 10 and when I call CType(GridView.Rows(i).FindControl("ID"), TextBox) it returns again 5! :(
Could someone help me? |
|
|
|
|
|
Subject: Afroditi
Name: How to keep user's value???
Date: 4/1/2009 2:54:10 AM
Comment: hi..again!pramod thanks for your reply but i don't need the value to update the gridview.
I want it to make a calculation and if the user wants to keep the result,then update it(i already create the code to update).
I found the way to keep the value (you have to convert the field you want to TemplateField and use CType(CountryInfoGridView.Rows(1).FindControl("TextBox1"), TextBox). But i cannot keep the user's value.
e.x.: if the initialized value is 5 i get from CType(CountryInfoGridView.Rows(1).FindControl("TextBox1"), TextBox) 5.But when the user insert 10 i get CType(CountryInfoGridView.Rows(1).FindControl("TextBox1"), TextBox)= 5 again...???????
|
|
|
|
|
|
Subject: How to keep user's value?
Name: gs
Date: 5/4/2009 8:41:15 AM
Comment: Hi Afroditi,
Can you please send the code lines for reading the itemtemplate of templatefield textbox values entered by the user on edit screen.
Thanks
gs |
|
|
|
|
|
Subject: Update All Rows of grid view at once
Name: Chanzeb Chaudhary
Date: 3/21/2010 5:43:55 AM
Comment: Hey!!!
its nice to see... |
|
|
|