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