Click here to Skip to main content
13,248,107 members (35,130 online)
Click here to Skip to main content
Add your own
alternative version

Stats

8.2K views
274 downloads
10 bookmarked
Posted 23 Dec 2015

Single-cell Editable GridView

, 4 Jan 2016
Rate this:
Please Sign up or sign in to vote.
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: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.

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).

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)

Share

About the Author

Zdenek CZ
Czech Republic Czech Republic
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 4 Jan 2016
Article Copyright 2015 by Zdenek CZ
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid