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 theGridView, 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

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.

  1. <Columns>
  2. <asp:ButtonField Text="SingleClick" CommandName="SingleClick"
  3. Visible="False" />
  4. </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 TextBoxDropdownList or CheckBox the "edit control".

  1. <asp:TemplateField HeaderText="Task">
  2. <ItemTemplate>
  3.  
  4. <asp:Label ID="DescriptionLabel" runat="server"
  5. Text='<%# Eval("Description") %>'></asp:Label>
  6.  
  7. <asp:TextBox ID="Description" runat="server"
  8. Text='<%# Eval("Description") %>' Width="175px"
  9. visible="false">

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

  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  2. {
  3. if (e.Row.RowType == DataControlRowType.DataRow)
  4. {
  5. // Get the LinkButton control in the first cell
  6. LinkButton _singleClickButton = (LinkButton)e.Row.Cells[].Controls[];
  7. // Get the javascript which is assigned to this LinkButton
  8. string _jsSingle = ClientScript.GetPostBackClientHyperlink(
  9. _singleClickButton, "");
  10.  
  11. // Add events to each editable cell
  12. for (int columnIndex = _firstEditCellIndex; columnIndex <
  13. e.Row.Cells.Count; columnIndex++)
  14. {
  15. // Add the column index as the event argument parameter
  16. string js = _jsSingle.Insert(_jsSingle.Length - ,
  17. columnIndex.ToString());
  18. // Add this javascript to the onclick Attribute of the cell
  19. e.Row.Cells[columnIndex].Attributes["onclick"] = js;
  20. // Add a cursor style to the cells
  21. e.Row.Cells[columnIndex].Attributes["style"] +=
  22. "cursor:pointer;cursor:hand;";
  23. }
  24. }
  25. }

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.

  1. int _rowIndex = int.Parse(e.CommandArgument.ToString());
  2. 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.

  1. // Get the display control for the selected cell and make it invisible
  2. Control _displayControl =
  3. _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[];
  4. _displayControl.Visible = false;
  5. // Get the edit control for the selected cell and make it visible
  6. Control _editControl =
  7. _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[];
  8. _editControl.Visible = true;
  9. // Clear the attributes from the selected cell to remove the click event
  10. _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 aDropDownList, 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.

  1. // Set focus on the selected edit control
  2. ClientScript.RegisterStartupScript(GetType(), "SetFocus",
  3. "<script>document.getElementById(
  4. '" + _editControl.ClientID + "').focus();</script>");
  5. // If the edit control is a dropdownlist set the
  6. // SelectedValue to the value of the display control
  7. if (_editControl is DropDownList && _displayControl is Label)
  8. {
  9. ((DropDownList)_editControl).SelectedValue = (
  10. (Label)_displayControl).Text;
  11. }
  12. // If the edit control is a textbox then select the text
  13. if (_editControl is TextBox)
  14. {
  15. ((TextBox)_editControl).Attributes.Add("onfocus", "this.select()");
  16. }
  17. // If the edit control is a checkbox set the
  18. // Checked value to the value of the display control
  19. if (_editControl is CheckBox && _displayControl is Label)
  20. {
  21. (CheckBox)_editControl).Checked = bool.Parse(((Label)_displayControl).Text);
  22. }

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.

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

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.

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

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.

  1. protected override void Render(HtmlTextWriter writer)
  2. {
  3. foreach (GridViewRow r in GridView1.Rows)
  4. {
  5. if (r.RowType == DataControlRowType.DataRow)
  6. {
  7. for (int columnIndex = _firstEditCellIndex; columnIndex <
  8. r.Cells.Count; columnIndex++)
  9. {
  10. Page.ClientScript.RegisterForEventValidation(
  11. r.UniqueID + "$ctl00", columnIndex.ToString());
  12. }
  13. }
  14. }
  15.  
  16. base.Render(writer);
  17. }

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

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

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)

download:

  1. http://pan.baidu.com/s/1pLL9bCJ

Edit Individual GridView Cells in ASP.NET的更多相关文章

  1. Asp.net中GridView详解《转》

    ASP.NET服务器控件GridView 1         ASP.NET 服务器控件GridView使用 本教程不介绍服务器端控件的呈现,事件处理,状态等理论知识,只介绍服务器端控件的使用操作,如 ...

  2. 在ASP.NET MVC5中实现具有服务器端过滤、排序和分页的GridView

    背景 在前一篇文章<[初学者指南]在ASP.NET MVC 5中创建GridView>中,我们学习了如何在 ASP.NET MVC 中实现 GridView,类似于 ASP.NET web ...

  3. [转]在ASP.NET MVC5中实现具有服务器端过滤、排序和分页的GridView

    本文转自:http://www.cnblogs.com/powertoolsteam/p/MVC5_GridView_2.html 背景 在前一篇文章<[初学者指南]在ASP.NET MVC 5 ...

  4. 利用ASP.NET AJAX的Timer讓GridView每隔一段時間做到自動換頁的功能

    最近在討論區看到這個問題,小弟利用asp.net ajax的timer來實作這個功能 利用timer每隔一段時間,讓gridview自動跳頁並且更新gridview的內容 asp.net(c#) Gr ...

  5. asp.net gridview实现正在加载效果方案一AJAX(转)

    前台代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.as ...

  6. asp.net存储过程分页+GridView控件 几百万数据 超快

    存储过程:---亲测275万数据,分页速度N快 ))+' '+@orderid+' from '+@tablename+' '+@tmpOrderid set @sql='select top'+st ...

  7. ASP.NET的gridview设置数据格式(DataFormatString="{}") 2011年04月08日 16:26:00 阅读数:5318 标签: asp.net datagrid integer asp date strin

    select convert(numeric(8,2),round(UnTaxAmount,2))as UnTaxAmount from View_SaleVoiceselect   cast(UnT ...

  8. Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api Ind ...

  9. GridView/DataGrid行单击和双击事件实现代码_.Net教程

    功能: 单击选中行,双击打开详细页面 说明:单击事件(onclick)使用了 setTimeout 延迟,根据实际需要修改延迟时间 ;当双击时,通过全局变量 dbl_click 来取消单击事件的响应  ...

随机推荐

  1. python返回null和空的不同

    mysql数据库中有的字段是NULL, 有的字段是空白 写Python脚本,fetchall()得到结果,也是不同. NULL对应的是None, 空白对应的是'' (None, '') 所以根据结果进 ...

  2. 理解iaas paas saas三种云服务区别

    其实搞懂这个问题也不难,我们可以把云计算理解成一栋大楼,而这栋楼又可以分为顶楼.中间.低层三大块.那么我们就可以把Iass(基础设施).Pass(平台).Sass(软件)理解成这栋楼的三部分.基础设施 ...

  3. 关于:1.指针与对象;2.深浅拷贝(复制);3.可变与不可变对象;4.copy与mutableCopy的一些理解

    最近对深浅拷贝(复制)做了一些研究,在此将自己的理解写下来,希望对大家有所帮助.本人尚处在摸索阶段,希望各位予以指正. 本文包括如下方向的探索: 1.指针与对象: 2.深/浅拷贝(复制): 3.可变/ ...

  4. 初识Spark(Spark系列)

    1.Spark Spark是继Hadoop之后,另外一种开源的高效大数据处理引擎,目前已提交为apach顶级项目. 效率: 据官方网站介绍,Spark是Hadoop运行效率的10-100倍(随内存计算 ...

  5. spark-2.0.0与hive-1.2.1整合

    SparkSQL与Hive的整合 1. 拷贝$HIVE_HOME/conf/hive-site.xml和hive-log4j.properties到 $SPARK_HOME/conf/ 2. 在$SP ...

  6. 关于c语言变量的内存分布测试程序

    #include <stdio.h> #include <stdlib.h> ; // 常全局变量 ; // 初始化全局变量 int uninit_global; // 未初始 ...

  7. Spring的字符编码过滤器CharacterEncodingFilter

    Spring中的字符编码过滤器,用来解决我们项目中遇到的编码问题. 使用方式特别友好,在web.xml加入: <filter> <description>字符集过滤器</ ...

  8. VMWARE player 如何让 win2012 guest os 支持HYPER-V

    在 vm player 下安装了 win2012 r2, 但是启用 hyper-v的时候,提示不支持, 这时候要修改 Open the file Location for this Virtual M ...

  9. [妙味DOM]第六课:鼠标滚轮和COOKIE

    知识点总结: 鼠标滚轮事件 存在兼容性问题: IE/chorme : onmousewheel FF : DOMMouseScroll,必需用在addEventListener下,例如: if (ob ...

  10. java 邮件发送 apache commons-email

    package com.sun.mail;import org.apache.commons.mail.Email;import org.apache.commons.mail.EmailExcept ...