Edit individual GridView Cells in ASP.

Source: Internet
Author: User
Tags sql server express

Edit individual GridView cells without putting the entire row into edit mode. Examples using the SqlDataSource and ObjectDataSource controls are included.

Introduction

The ASP GridView . Allows for a row of data to being edited by setting EditIndex GridView The property of the, placing the entire row In edit mode.

Want the entire row in edit mode if is using DropDownList controls for several columns in the EditItemTemplate . If each have DropDownList many options, then loading them all at once the 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'll demonstrate how to achieve this and also what to deal with Event Validation without disabling it.

Background

This article are based on questions I am asked in relation to one of my previous articles:clickable and Double clickable Rows with the GridView and DataList Controls in ASP.

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

Edit individual GridView Cells

The In the demo has a control called in the first column with its GridView  asp:ButtonField SingleClick  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 are an item template with a visible Label control and an invisible TextBox , DropdownList or c15/> control.

For convenience, we'll call the Label "Display control" TextBox and the, 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">

The idea of this is the initially the data was displayed in the display control and when the cell containing the display cont Rol is clicked, it's visibility is set to and the false edit control's visibility is set to true . The is isn't EditItemTemplate used.

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

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

protected voidGridView1_RowDataBound (Objectsender, GridViewRowEventArgs e) {    if(E.row.rowtype = =datacontrolrowtype.datarow) {//Get the LinkButton control in the first cellLinkButton _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(intColumnIndex = _firsteditcellindex; ColumnIndex <E.row.cells.count; ColumnIndex++)        {            //Add the column index as the event argument parameter            stringJS = _jssingle.insert (_jssingle.length-2, columnindex.tostring ()); //Add This javascript to the onclick Attribute of the cellE.row.cells[columnindex]. attributes["onclick"] =JS; //Add a cursor style to the cellsE.row.cells[columnindex]. attributes["style"] +="Cursor:pointer;cursor:hand;"; }    }}

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

int int . Parse (E.commandargument.tostring ()); int int. Parse (request.form["__eventargument"]);

Since the row and column indexes of the selected cell is known, the cell can be set to edit mode by setting the Visibilit Y of the display control to and which of the false edit control to true .

The attributes of the selected cell is also cleared to remove the Click event.

//Get the display control for the selected cell and make it invisibleControl _displaycontrol =_gridview.rows[_rowindex]. Cells[_columnindex]. controls[1];_displaycontrol.visible=false;//Get the edit control for the selected cell and make it visibleControl _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 and then SelectedValue it's set to the value of the display control, if it's a then its TextBox text I s selected so that it was ready for editing and if it was a then its checked value was set to that of the Checkbox display contr Ol.

//Set focus on the selected edit controlClientscript.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 controlif(_editcontrol isDropDownList && _displaycontrol isLabel) {((DropDownList) _editcontrol). SelectedValue=((Label) _displaycontrol). Text;}//If The Edit control is a textbox then select the textif(_editcontrol isTextBox) {(TextBox) _editcontrol). Attributes.Add ("onfocus","This.select ()");}//If The Edit control is a checkbox set the//Checked value to the value of the display controlif(_editcontrol isCheckBox && _displaycontrol isLabel) {(CheckBox) _editcontrol). Checked=BOOL. Parse ((Label) _displaycontrol). Text);}

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

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 this RowUpdating is fired after a cell is edited, it's called in Page_Load . By hitting "Enter" after editing a TextBox or clicking another cell, the page was posted back and the checks was made to Ensu Re any data changes is saved.

if (this.) Gridview1.selectedindex >-1) {    this. Gridview1.updaterow (thisfalse);}
Register the Postback or Callback Data for Validation

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

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

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

protected Override voidRender (HtmlTextWriter writer) {foreach(GridViewRow Rinchgridview1.rows) {if(R.rowtype = =datacontrolrowtype.datarow) { for(intColumnIndex = _firsteditcellindex; ColumnIndex <R.cells.count; ColumnIndex++) {Page.ClientScript.RegisterForEventValidation (R.uniqueid+"$ctl xx", columnindex.tostring ()); }        }    }    Base. Render (writer);}

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

Other Examples in the Demo projectediting 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 populate the NewValues collection when updating a GridView  row.

EditItemTemplateas the is isn't being used in this scenario and 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 config, you could need to modify the connection string in the Web.

Editing individual GridView Cells Using an Object Data Source Control

This example uses the 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 this in the SQL Data Source example.

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

GridView with Spreadsheet styling

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

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

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

GridView with Spreadsheet styling Using a SQL Data Source Control

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

References
    • Clickable and Double clickable Rows with GridView and DataList Controls in ASP. Declan Bright
    • Data Access Tutorials
Conclusion

If you want to edit the data in an ASP GridView . One cell at a time, and then this technique is useful.

History
    • v1.0-25th Mar 2007
    • v2.0-7th APR 2007
      • Examples using and added to the SqlDataSource  ObjectDataSource  demo Project
    • v3.0-23rd Nov 2007
      • Examples with paging and sorting added to the demo project
      • ASP. 3.5 Web. config added to demo project
    • v4.0-5th Nov 2009
      • Examples UpdatePanel with, 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)

Download

http://PAN.BAIDU.COM/S/1PLL9BCJ

Edit individual GridView Cells in ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.