65.9K
CodeProject is changing. Read more.
Home

Single-cell Editable GridView

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (6 votes)

Dec 23, 2015

CPOL

1 min read

viewsIcon

18203

downloadIcon

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