Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Single-cell Editable GridView

4.75/5 (6 votes)
4 Jan 2016CPOL1 min read 18.2K   554  
Let's go to write ASP.NET GridView with the ability to edit cell on click and save the changes on Enter

Introduction

In one of my projects, I need to edit data in GridView so that the user can edit only an individual cell and data would be saved into the database by pressing Enter or clicking on another cell. At the same time, I need access data from cells that have been modified. Now, when I see the result, it seems clear and easy to me, so I would like to share it with you.

Single-cell editable GridView preview

Using the Code

My solution is based on a standard GridView and I use a Label control for displaying data, TextBox for editing and Button to save changed data.

ASP.NET
<asp:TemplateField HeaderText="Author" SortExpression="Author">
   <ItemTemplate>
   <asp:Label ID="labAuthor" runat="server" 
   Text='<%# Eval("author") %>'></asp:Label>
   <asp:TextBox ID="txtAuthor" runat="server" 
   Text="<%# Eval('author') %>" Width="175px" style="display:none" ></asp:TextBox>
   <asp:Button id="btnAuthor" runat="server" OnCommand="txtAuthor_Changed" style="display:none" />
   </ItemTemplate>
</asp:TemplateField>

The controls are displayed or hidden by JavaScript as well as “clicking” a button. Relevant JS functions are added to the controls from code-behind in the RowDataBound event because we need to obtain the client-side unique ID.

JavaScript
lab.Attributes.Add("onclick", string.Format("return HideLabel('{0}', 
	event, '{1}');", lab.ClientID, txt.ClientID));

Server-side events of the buttons can be used to execute server-side code, e.g., save to DB. Information about row and cell index are stored in CommandEventArgs (I know, this is not the best way, but it is working and as far as I know, there is no security issue).

C#
protected void txtAuthor_Changed(object sender, CommandEventArgs e)
{
   int row = int.Parse(e.CommandName);
   int cell = int.Parse(e.CommandArgument.ToString());
}

Points of Interest

There is an opportunity for improvement, e.g., to free CommandEventArgs of buttons. All comments are welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)