Click here to Skip to main content
15,891,184 members
Articles / Web Development / ASP.NET
Tip/Trick

Single-cell Editable GridView

Rate me:
Please Sign up or sign in to vote.
4.75/5 (6 votes)
4 Jan 2016CPOL1 min read 17.8K   550   10   1
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)


Written By
Czech Republic Czech Republic
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGitHub Pin
Zdenek CZ14-Nov-22 3:53
Zdenek CZ14-Nov-22 3:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.