Click here to Skip to main content
Click here to Skip to main content
Go to top

Edit Individual GridView Cells in ASP.NET

, 14 Nov 2009
Rate this:
Please Sign up or sign in to vote.
Edit individual GridView cells without putting the entire row into edit mode.Examples using the SqlDataSource and ObjectDataSource controls are included.

Introduction

The ASP.NET GridView allows for a row of data to be edited by setting the EditIndex property of the GridView, placing the entire row in edit mode.

You may not want the entire row in edit mode if you are using DropDownList controls for several columns in the EditItemTemplate. If each DropDownList has many options, then loading them all at once may result in a sluggish page. Also, if your data structure is more like a 2 dimensional array rather than a set of rows, you may want to edit each cell individually.

Here I will demonstrate how to achieve this and also how to deal with Event Validation without disabling it.

Background

This article is based on questions I was asked in relation to one of my previous articles: Clickable and Double Clickable Rows with GridView and DataList Controls in ASP.NET.

To understand the concept of making a GridView row clickable, you may want to read it before proceeding.

Edit Individual GridView Cells

Screenshot - EditGridviewCells1.jpg

The GridView in the demo has an asp:ButtonField control called SingleClick in the first column with its visibility set to false.

This is used to add the click event to the GridView rows.

<Columns>
    <asp:ButtonField Text="SingleClick" CommandName="SingleClick"
                        Visible="False" />
</Columns>

For each of the other columns, there is an item template with a visible Label control and an invisible TextBox, DropdownList or CheckBox control.

For convenience, we will call the Label the "display control" and the TextBox, DropdownList or CheckBox the "edit control".

<asp:TemplateField HeaderText="Task">
    <ItemTemplate>

        <asp:Label ID="DescriptionLabel" runat="server"
            Text='<%# Eval("Description") %>'></asp:Label>

        <asp:TextBox ID="Description" runat="server"
            Text='<%# Eval("Description") %>' Width="175px"
            visible="false"></asp:TextBox>

    </ItemTemplate>
</asp:TemplateField>

The idea here is that initially the data is displayed in the display control and when the cell containing the display control is clicked, it's visibility is set to false and the edit control's visibility is set to true. The EditItemTemplate is not used.

Within the RowDataBound event, each cell of the row is looped through and has a click event added.

The cell index is passed in as the event argument parameter so that the cell can be identified when it raises an event.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Get the LinkButton control in the first cell
        LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
        // Get the javascript which is assigned to this LinkButton
        string _jsSingle = ClientScript.GetPostBackClientHyperlink(
            _singleClickButton, "");

        // Add events to each editable cell
        for (int columnIndex = _firstEditCellIndex; columnIndex <
            e.Row.Cells.Count; columnIndex++)
        {
            // Add the column index as the event argument parameter
            string js = _jsSingle.Insert(_jsSingle.Length - 2,
                columnIndex.ToString());
            // Add this javascript to the onclick Attribute of the cell
            e.Row.Cells[columnIndex].Attributes["onclick"] = js;
            // Add a cursor style to the cells
            e.Row.Cells[columnIndex].Attributes["style"] +=
                "cursor:pointer;cursor:hand;";
        }
    }
}

Within the RowCommand event, the command argument and the event argument are retrieved. This gives us the row and column index of the selected cell.

int _rowIndex = int.Parse(e.CommandArgument.ToString());
int _columnIndex = int.Parse(Request.Form["__EVENTARGUMENT"]);

Since the row and column indexes of the selected cell are known, the cell can be set to edit mode by setting the visibility of the display control to false and that of the edit control to true.

The attributes of the selected cell are also cleared to remove the click event.

// Get the display control for the selected cell and make it invisible
Control _displayControl =
    _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[1];
_displayControl.Visible = false;
// Get the edit control for the selected cell and make it visible
Control _editControl =
    _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[3];
_editControl.Visible = true;
// Clear the attributes from the selected cell to remove the click event
   _gridView.Rows[_rowIndex].Cells[_columnIndex].Attributes.Clear();

There is also some code to set the focus on the edit control after a postback. If the edit control is a DropDownList, then its SelectedValue is set to the value of the display control, if it is a TextBox then its text is selected so that it is ready for editing and if it is a Checkbox then its checked value is set to that of the display control.

// Set focus on the selected edit control
ClientScript.RegisterStartupScript(GetType(), "SetFocus",
    "<script>document.getElementById(
    '" + _editControl.ClientID + "').focus();</script>");
// If the edit control is a dropdownlist set the
// SelectedValue to the value of the display control
if (_editControl is DropDownList && _displayControl is Label)
{
    ((DropDownList)_editControl).SelectedValue = (
        (Label)_displayControl).Text;
}
// If the edit control is a textbox then select the text
if (_editControl is TextBox)
{
   ((TextBox)_editControl).Attributes.Add("onfocus", "this.select()");
}
// If the edit control is a checkbox set the
// Checked value to the value of the display control
if (_editControl is CheckBox && _displayControl is Label)
{
    (CheckBox)_editControl).Checked = bool.Parse(((Label)_displayControl).Text);
}

In the demo, a history of the events fired is also written to the page. Within RowUpdating each cell in the row is checked to see if it is in edit mode. If a cell in edit mode is found, then the data update code is called.

In the first demo page, some sample data is held in a DataTable which is stored in session.

// Loop though the columns to find a cell in edit mode
for (int i = 1; i < _gridView.Columns.Count; i++)
{
    // Get the editing control for the cell
    Control _editControl = _gridView.Rows[e.RowIndex].Cells[i].Controls[3];
    if (_editControl.Visible)
    {
       .... update the data
    }
}

To ensure that RowUpdating is fired after a cell is edited, it is called in Page_Load. By hitting "Enter" after editing a TextBox or clicking another cell, the page is posted back and the checks are made to ensure any data changes are saved.

if (this.GridView1.SelectedIndex > -1)
{
    this.GridView1.UpdateRow(this.GridView1.SelectedIndex, false);
}

Register the Postback or Callback Data for Validation

The custom events created in RowDataBound must be registered with the page.

The ClientScriptManager.RegisterForEventValidation is called by overriding the Render method.

The UniqueID of the row is returned by GridViewRow.UniqueID and the UniqueID of the button can be generated by appending "$ctl00" to the row's UniqueID.

protected override void Render(HtmlTextWriter writer)
{
    foreach (GridViewRow r in GridView1.Rows)
    {
        if (r.RowType == DataControlRowType.DataRow)
        {
            for (int columnIndex = _firstEditCellIndex; columnIndex <
                r.Cells.Count; columnIndex++)
            {
                Page.ClientScript.RegisterForEventValidation(
                    r.UniqueID + "$ctl00", columnIndex.ToString());
            }
        }
    }

    base.Render(writer);
}

This will prevent any "Invalid postback or callback argument" errors from being raised.

Other Examples in the Demo Project

Editing Individual GridView Cells Using a SQL Data Source Control

Implementing this technique with a SqlDataSource control requires some modifications to the GridView's RowUpdating event. A SqlDataSource control normally takes the values from the EditItemTemplate to populate the NewValues collection when updating a GridView row.

As the EditItemTemplate is not being used in this scenario, the NewValues collection must be populated programmatically.

e.NewValues.Add(key, value);

There is a simple SQL Server Express database in the App_Data folder for the data.

(Depending on your configuration, you may need to modify the connection string in the web.config).

Editing Individual GridView Cells Using an Object Data Source Control

This example uses the two classes in the App_Code folder:

  • Task.cs - is the Task object
  • TaskDataAccess.cs - manages the Task object

The code behind of the ASPX page is identical to that in the SQL Data Source example.

The ObjectDataSource manages the data through the GetTasks and UpdateTask methods in the TaskDataAccess.cs class.

GridView with Spreadsheet Styling

This example has a GridView which is styled to look like a spreadsheet.

(Although it looks like a spreadsheet, it does not really behave like a spreadsheet, it's still a GridView after all!)

The principle is the same as above although there is some extra code which changes the cell styles when they are clicked, etc.

Screenshot - EditGridviewCells2.jpg

GridView with Spreadsheet Styling Using a SQL Data Source Control

This example is the same as above but with some modifications to the GridView's RowUpdating event to allow it to work with a SqlDataSource control.

References

Conclusion

If you want to edit data in an ASP.NET GridView one cell at a time, then this technique may be useful.

History

  • v1.0 - 25th Mar 2007
  • v2.0 - 7th Apr 2007
    • Examples using SqlDataSource and ObjectDataSource added to the demo project
  • v3.0 - 23rd Nov 2007
    • Examples with paging and sorting added to the demo project
    • ASP.NET 3.5 web.config added to demo project
  • v4.0 - 5th Nov 2009
    • Examples with UpdatePanel, Validator Controls, and CheckBox added to the demo project
    • VB.NET examples added to demo project

License

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

Share

About the Author

Declan Bright
Architect
Ireland Ireland
I have been designing and developing business solutions for the aviation and telecommunications industries since 1999. My experience covers a wide range of technologies and I have delivered a variety of web and mobile based solutions.

Comments and Discussions

 
QuestionSlow Performance Issue PinmemberMember 195826520-Jan-14 1:46 
QuestionTab through edit controls PinmemberRavensDave16-Aug-13 4:25 
GeneralMy vote of 5 PinprofessionalMohamedKamalPharm12-Jun-13 2:56 
GeneralMy vote of 4 PinmemberWebBHTAN22-Feb-13 1:45 
Questionmultiple data sources Pinmemberhussyass27-Jul-12 12:09 
QuestionDeleting a row PinmemberMember 81196449-Apr-12 12:58 
QuestionHandling Tab key Pinmembereliaso54-Jan-12 12:04 
GeneralMy vote of 4 PinmemberVarun Sareen28-Dec-11 18:19 
GeneralGetting an Error Pinmembereliaso517-Dec-11 18:01 
GeneralMy vote of 5 PinmemberRaviRanjankr13-Nov-11 4:27 
GeneralMy vote of 5 PinmemberAnurag Gandhi2-Oct-11 20:45 
QuestionNice article PinmemberJohn Felix5-Jul-11 19:28 
GeneralIndex out of range PinmemberGene Lamm4-Jun-11 1:32 
GeneralRe: Index out of range PinmemberDave Vroman3-Mar-14 8:40 
GeneralIndex was out of range Pinmemberchitmm20-Mar-11 22:04 
GeneralRe: Index was out of range PinmemberMember 402313031-Oct-11 3:35 
GeneralRe: Index was out of range PinmemberMember 402313031-Oct-11 3:36 
GeneralFor Select,Insert,Update and Delete in GridView without writting C# or Vb Code Pinmembervijay_vignesh26-Jan-11 1:20 
QuestionHow to set the Label width to fixed value in gridview? PinmemberG.Suman Babu13-Jan-11 3:16 
QuestionCopy data from multiple cells and paste into another group of cells? PinmembersKyaHbOy28-Dec-10 21:28 
GeneralMy vote of 5 PinmemberSTRICQ23-Dec-10 12:42 
GeneralI need to show the entire been selected however, need only a particular cell on that row to be selectable and updateable PinmemberMember 280198415-Nov-10 7:32 
GeneralMy vote of 5 Pinmemberuma ashankar26-Oct-10 3:22 
GeneralAchiving Editable individual gridview cells for dynamically bind grid. Pinmemberb_rajmalla5-Oct-10 3:42 
GeneralMy vote of 1 Pinmembermathizory5-Aug-10 21:53 
GeneralMy vote of 4 PinmemberMember 404700420-Jul-10 23:49 
GeneralUse in Web User Control [modified] Pinmembercalin7426-Apr-10 22:22 
GeneralFocus to the control fails. Can you help me? - Can't move focus to the control because it is invisible... PinmemberMember 33470136-Apr-10 9:59 
GeneralRe: Focus to the control fails. Can you help me? - Can't move focus to the control because it is invisible... PinmemberMember 33470139-Apr-10 10:16 
GeneralCancelling the Update Mode Pinmemberdpreznik2-Apr-10 6:20 
QuestionDynamic GridViews (OK) - MasterPage ? PinmemberPDTPGY18-Mar-10 23:20 
AnswerRe: Dynamic GridViews (OK) - MasterPage ? PinmemberPDTPGY12-Apr-10 22:01 
QuestionDynamic GridViews PinmemberPDTPGY18-Mar-10 7:08 
QuestionCheck Box Problem PinmemberimatureStudent10-Feb-10 23:03 
AnswerRe: Check Box Problem PinmemberDeclan Bright10-Feb-10 23:25 
GeneralRe: Check Box Problem PinmemberimatureStudent12-Feb-10 1:19 
GeneralError here PinmemberSRKVELLANKI11-Dec-09 7:02 
GeneralEditing finish PinmemberNZibir8-Dec-09 21:13 
AnswerRe: Editing finish PinmemberDeclan Bright8-Dec-09 21:28 
GeneralRe: Editing finish PinmemberNZibir9-Dec-09 1:04 
GeneralRe: Editing finish PinmemberDeclan Bright9-Dec-09 3:02 
GeneralRe: Editing finish [modified] PinmemberNZibir9-Dec-09 4:26 
GeneralRe: Editing finish PinmemberSteveZodiac17-Feb-10 9:01 
QuestionAwesome work! Has anyone gotten this to work in VS2008 with VB.NET? PinmemberMichael Veltre18-Aug-09 18:15 
AnswerRe: Awesome work! Has anyone gotten this to work in VS2008 with VB.NET? PinmemberDeclan Bright18-Aug-09 21:16 
GeneralRe: Awesome work! Has anyone gotten this to work in VS2008 with VB.NET? PinmemberMichael Veltre19-Aug-09 5:15 
GeneralRe: Awesome work! Has anyone gotten this to work in VS2008 with VB.NET? PinmemberMichael Veltre20-Aug-09 5:32 
GeneralGreat work very helpful! Pinmemberbobk5449-Aug-09 3:55 
GeneralThis is Brilliant welldone man!!! PinmemberMember 139247430-Jul-09 2:06 
QuestionAjax Enabling PinmemberMember 26252632-Jun-09 19:35 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 14 Nov 2009
Article Copyright 2007 by Declan Bright
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid