原文:asp.net学习之GridView事件、GridViewRow对象

1. GridView控件的事件

GridView有很多事件,事件可以定制控件的外观或者行为。事件分为三类
    1.1 GridView显示数据时的事件
          ● DataBinding : 在绑定数据源之前触发 [继承自Control]
          ● DataBound 在绑定到数据源后触发
          ● RowCreated 创建每一行时触发
          ● RowDataBound : 每一行绑定完数据时触发

              MSDN解释:呈现 GridView 控件之前,必须先为该控件中的每一行创建一个 GridViewRow 对象。在创建 GridView 控件中的每一行时,将引发 RowCreated 事件。这使您可以提供一个这样的事件处理方法,即每次发生此事件时就执行一个自定义例程(如在行中添加自定义内容)。
例1:使用 RowCreated 事件将正在创建的行的索引存储在该行所包含 LinkButton 控件的 CommandArgument 属性中

Code<script runat="server">protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e){    if(e.CommandName=="Add")    {        int index = Convert.ToInt32(e.CommandArgument);        GridViewRow gvRow = GridView2.Rows[index];        ListItem item = new ListItem();  // 创建ListItem项        item.Text = Server.HtmlDecode(gvRow.Cells[2].Text);        if(!ListBox1.Items.Contains(item))  //如果还没有包含该项        {            ListBox1.Items.Add(item);        }    }}protected void GridView2_RowCreated(object sender, GridViewRowEventArgs e){    if(e.Row.RowType == DataControlRowType.DataRow)    {        // 获得第一列的LinkButton控件对象        LinkButton addLink = (LinkButton)e.Row.Cells[0].Controls[0];        // 给Link控件CommandArgmenut参数赋值,值为当前的索引        addLink.CommandArgument = e.Row.RowIndex.ToString();     }}</script><asp:GridView ID="GridView2" runat="server" AllowPaging="True"  AutoGenerateColumns="False" PageIndex="10"            onrowcommand="GridView2_RowCommand" onrowcreated="GridView2_RowCreated">           <Columns>               <asp:ButtonField ButtonType="Link" CommandName="Add" Text="Add" />               <asp:BoundField DataField="Id" SortExpression="Id" HeaderText="编号" />               <asp:BoundField DataField="Description" HeaderText="描述" />           </Columns>           <PagerSettings Mode="NumericFirstLast" Position="Bottom" />           <PagerStyle HorizontalAlign="Center" /></asp:GridView><asp:ListBox ID="ListBox1" runat="server"></asp:ListBox> 

例2:使用 RowDataBound 事件在数据源中的字段值显示在 GridView 控件中之前修改该值。

Codeprotected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e){    if(e.Row.RowType==DataControlRowType.DataRow)    {        e.Row.Cells[].Text = "<i>" + e.Row.Cells[].Text + "</i>";        // 也可以使用DataBinder.Eval取得相应Cell内的值       decimal boxOfficeTotal = (decimal)DataBinder.Eval(e.Row.DataItem,”BoxOfficeTotals”);       if(boxOfficeTotal > )           e.Row.BackColor = System.Drawing.Color.Yellow;    }} 

以上,在RowCreated,RowDataBound事件中,都有一个参数为GridViewRowEventArgs的对象,通过该对象,可以访问相应的GridViewRow对象。
     【而GridViewRow对象的一些东西,在下面会单独来讲述。】

1.2 GridView编辑数据时的事件
          ● RowCommand 当GridView中的控件引发事件时触发
               RowCommand触发时,有一个参数GridViewCommandEventArgs对象,通过它,可以知道CommandName,CommandArgument,见例11
          ● RowUpdating 当GridView更新记录前触发
               RowUpdating 事件发生时,有一个参数为GridViewUpdateEventArgs的对象,其有一些属性有用处
                 ▲ Cancel : 应取消事件,则为 true;否则为 false
                 ▲ Keys : 包含已更新记录的键字段名称/值对的字典
                 ▲ NewValues:包含已更新记录的新字段的名称/值对的字典
                 ▲ OldValues:包含被更新记录的原始字段名称/值对的字典
                 ▲ RowIndex: 所更新的行的索引
          ● RowUpdated  当GridView更新记录后触发
               RowUpdated事件发生时,有一个参数为GridViewUpdatedEventArgs的对象。其有一些属性在更新时很有用处
                 ▲ AffectedRows: 受更新操作影响的行数
                 ▲ Exception : 更新操作过程中引发的异常。如果未引发异常,此属性将返回 null
                 ▲ ExceptionHandled:异常已在事件处理程序中得到处理,则为 true,异常不会被再次引发;否则为 false
                 ▲ KeepInEditMode:如果在完成更新操作之后该控件继续处于编辑模式,则为 true;否则为 false
                 ▲ Keys : 包含已更新记录的键字段名称/值对的字典
                 ▲ NewValues:包含已更新记录的新字段的名称/值对的字典
                 ▲ OldValues:包含被更新记录的原始字段名称/值对的字典
               注意与RowUpdating事件发生时,事件参数类的区别
          ● RowDeleting 当GridView删除记录前触发
               RowDeleting事件发生时,有一个参数为GridViewDeleteEventArgs的对象,其有一些属性
                  ▲ Cancel、Keys、RowIndex、Values
                  以上,Values获取包含要删除的行的非键字段名称/值对的字典。其它的与RowUpdting时参数对象用法大同小异
          ● RowDeleted  当GridView删除记录后触发
               RowDeleted事件发生时,有一个参数为GridViewDeletedEventArgs的对象,其有一些属性
                  ▲ AffectedRows、Exception 、ExceptionHandled、Keys、Values,见RowUpdated时参数的用法
       ● RowCancelingEdit: 取消更新记录后触发
               单击编辑模式中某一行的“取消”按钮以后,将引发 RowCancelingEdit 事件,但在该行退出编辑模式之前。
               这使您可以提供一个这样的事件处理方法,例如,如果取消操作将行置于不希望有的状态,则停止该操作。
               RowCancelingEdit发生时,有一个名为GridViewCancelEditEventArgs对象的参数,包含两个属性:Cancel和RowIndex.
       ● RowEditing : 单击某一行的“编辑”按钮以后,GridView 控件进入编辑模式之前触发。
              这使您可以提供一个这样的事件处理方法,即每次发生此事件时就执行一个自定义例程(如取消编辑操作,不出现Edit框)。
              RowEditing事件发生时,有一个参数为GridViewEditEventArgs对象,它包括以下二个属性
                  ▲ Cancel : 是否编辑事件
                  ▲ NewEditIndex: 所编辑的行的索引。
例3:如何访问已更新记录的非键字段的原始值。

Code<script runat="server">  void CustomersGridView_RowUpdated(Object sender, GridViewUpdatedEventArgs e)  {    if (e.Exception == null)  {   // 如果更新没有异常      if (e.AffectedRows == 1) {  // 如果影响行数为1行        //使用Keys属性可以访问键字段名称/值,需要在GridView中设定DataKeyNames        String keyFieldValue = e.Keys["CustomerID"].ToString();         Message.Text = "Record " + keyFieldValue + " updated successfully. ";        // 显示新的和原有的旧的字段值,OrderedDictionary类表示键或索引可访问的键/值对的集合。        DisplayValues((OrderedDictionary)e.NewValues, (OrderedDictionary)e.OldValues);      }      else {  //如果影响行数为多行        Message.Text = "An error occurred during the update operation.";        e.KeepInEditMode = true;      }    }    else {  // 有异常发生      Message.Text = e.Exception.Message;      // Use the ExceptionHandled property to indicate that the exception is already handled.      e.ExceptionHandled = true;      e.KeepInEditMode = true;    }  }  // 显示OrderedDirctionary中的键/值对   void DisplayValues(OrderedDictionary newValues, OrderedDictionary oldValues)  {       Message.Text += "<br/></br>";.    for (int i = 0; i < oldValues.Count; i++) {      Message.Text += "Old Value=" + oldValues[i].ToString() +        ", New Value=" + newValues[i].ToString() + "<br/>";    }    Message.Text += "</br>";  }</script><asp:gridview id="CustomersGridView" datasourceid="CustomersSqlDataSource"        autogeneratecolumns="true" autogenerateeditbutton="true" allowpaging="true"        datakeynames="CustomerID" onrowupdated="CustomersGridView_RowUpdated"        runat="server"></asp:gridview> 

例4:控件中移除最后一条记录时,如何使用 RowDeleting 事件取消删除操作。

Code<script runat="server">void CustomersGridView_RowDeleting(Object sender, GridViewDeleteEventArgs e)  {    // Cancel the delete operation if the user attempts to remove    // the last record from the GridView control.    if (CustomersGridView.Rows.Count <= 1)    {      e.Cancel = true;      Message.Text = "You must keep at least one record.";    }  } </script> 

1.3 GridView选择、排序和分布事件
          ● PageIndexChanging: 击某一页导航按钮时,但在 GridView 控件处理分页操作之前发生。
              PageIndexChanging事件发生时,事件处理函数中会有一个GridViewPageEventArgs 对象的参数,该对象包含以下属性:
                ▲ Cancel : 获取或设置指示是否应取消事件的值
                ▲ NewPageIndex : 获取或设置要在 GridView 控件中显示的新页的索引。
          ● PageIndexChanged : 单击某一页导航按钮时,但在 GridView 控件处理分页操作之后发生。
              PageIndexChanged事件发生时,相应的参数是普通的EventArgs对象。
          ● Sorting : 在排序开始前触发
               事件发生时,会传递GridViewSortEventArgs对象参数,该对象包含以下属性
                ▲ Cancel : 获取或设置指示是否应取消排序
                ▲ SortDirection: 获取或设置排序方向。
                ▲ SortExpression: 获取或设置指控件中的项进行排序的表达式。
          ● Sorted: 排序操作进行处理之后触发
              事件发生时,相应的参数是普通的EventArgs对象。
          ● SelectedIndexChanging : 行被选中之前发生。
              事件发生时,会传递GridViewSelectEventHandler 对象参数,该对象包含以下属性
                ▲ Cancel : 获取或设置指示是否应取消选择
                ▲ NewSelectedIndex: 获取或设置要在 GridView 控件中选择的新行的索引
          ● SelectedIndexChanged : 行被选中之后发生。
              事件发生时,相应的参数是普通的EventArgs对象。
              注:在这个事件中,可以直接访问GridView.SelectedRow,以取得被选中的GridViewRow对象
例5:如何使用 NewPageIndex 属性确定用户所选择页面的索引。

Code<script runat="server">  void CustomersGridView_PageIndexChanging(Object sender, GridViewPageEventArgs e)  {    if (CustomersGridView.EditIndex != -1) {      // 如果正处在编辑模式,不进行分页      e.Cancel = true;      int newPageNumber = e.NewPageIndex + 1;      Message.Text = "Please update the record before moving to page " +        newPageNumber.ToString() + ".";    }    else {      Message.Text = ""; // Clear the error message.    }  }  void CustomersGridView_RowCancelingEdit(Object sender, GridViewCancelEditEventArgs e)  {    // Clear the error message.    Message.Text = "";  }</script> 

例6: 如何使用 SortExpression 属性确定正在对哪一列进行排序。如果对地址列进行排序,排序操作将被取消。

Code<script runat="server">  void CustomersGridView_Sorting(Object sender, GridViewSortEventArgs e)  {    if (e.SortExpression == "Address") {      e.Cancel = true;      Message.Text = "You cannot sort by address.";      SortInformationLabel.Text = "";    }  else{      Message.Text = "";    }  }  void CustomersGridView_Sorted(Object sender, EventArgs e)  {    // Display the sort expression and sort direction.      SortInformationLabel.Text = "Sorting by " +      CustomersGridView.SortExpression.ToString() +      " in " + CustomersGridView.SortDirection.ToString() +      " order.";  }</script>

2. GridViewRow对象

GridView 控件将其所有数据行都存储在 Rows 集合中。若要确定 Rows 集合中 GridViewRow 对象的索引,请使用 RowIndex 属性。
    对于WEB来说,一个GridViewRow,其实就相当于一个<tr></tr>行
    2.1 GridViewRow的类型(RowType)
      用于表示 GridView 控件中的单独行。GridView 控件中的每个行都有指定的行类型。下表列出了各种行类型。
       ● DataGridRowType.DataRow    : 数据行
       ● DataGridRowType.Footer       : 脚注行
       ● DataGridRowType.Header      : 标头行
       ● DataGridRowType.NullRow     : 空行,没有数据显示时,控件中将显示空行
       ● DataGridRowType.Pager        : 页导航
       ● DataGridRowType.Separator  : 分隔符行
     如果要确定GridViewRow对象的类型,请使用RowType属性

   2.2 GridViewRow的状态(RowState)
       ● DataControlRowState.Alternate    : 备用行状态
       ● DataControlRowState.Edit           : 行处于编辑状态
       ● DataControlRowState.Normal       : 行处于正常状态
       ● DataControlRowState.Selected     : 已选定GridViewRow对象
     若要确定 GridViewRow 对象的状态,请使用 RowState 属性。

   2.3 DataItem,Cells属性
       ● DataItem : GridViewRow 对象绑定到的基础数据对象。该属性只在发生 GridView 控件的 RowDataBound 事件时及在发生后才可用。
例7: 如何使用 DataItem 属性检索字段值。将该值用于预先选择在某一行处于编辑模式时显示的 DropDownList 控件中的某个项。

Code<script runat="server">void AuthorsGridView_RowDataBound (Object sender, GridViewRowEventArgs e)  {    // 是否处于编辑模式    if(e.Row.RowState == DataControlRowState.Edit) {      DataRowView rowView = (DataRowView)e.Row.DataItem;  // 获得编辑行的DataRowView对象      String state = rowView["state"].ToString();  // 通过DataRowView,可以直接取出某字段      DropDownList list = (DropDownList)e.Row.FindControl("StatesList"); // 获得StatesList的DropDownList对象      ListItem item = list.Items.FindByText(state);  // 找到DropDonList中的某一项      list.SelectedIndex = list.Items.IndexOf(item); // 选中那一项    }  }  void AuthorsGridView_RowUpdating(Object sender, GridViewUpdateEventArgs e)  {    GridViewRow row = AuthorsGridView.Rows[AuthorsGridView.EditIndex];    // Retrieve the DropDownList control from the row.    DropDownList list = (DropDownList)row.FindControl("StatesList");    e.NewValues["state"] = list.SelectedValue;  }</script><asp:gridview id="AuthorsGridView" datasourceid="AuthorsSqlDataSource"    autogeneratecolumns="false" autogenerateeditbutton="true" datakeynames="au_id"    onrowdatabound="AuthorsGridView_RowDataBound"    onrowupdating="AuthorsGridView_RowUpdating" runat="server">    <columns>       <asp:boundfield datafield="au_lname"  headertext="Last Name"/>       <asp:boundfield datafield="au_fname" headertext="First Name"/>       <asp:templatefield headertext="State">          <itemtemplate>  <%#Eval("state")%>  </itemtemplate>          <edititemtemplate>              <asp:dropdownlist id="StatesList" datasourceid="StatesSqlDataSource"                  datatextfield="state"  runat="server"/>               <asp:sqldatasource id="StatesSqlDataSource"  <!-- 在GridView模板中也可以加入SqlDataSource控件 -->                  selectcommand="SELECT Distinct [state] FROM [authors]"                  connectionstring="server=localhost;database=pubs;integrated security=SSPI"                  runat="server"> </asp:sqldatasource>           </edititemtemplate>                  </asp:templatefield>    </columns></asp:gridview><asp:sqldatasource id="AuthorsSqlDataSource"     selectcommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]"    updatecommand="UPDATE authors SET [au_lname]=@au_lname, [au_fname]=@au_fname, [state]=@state WHERE au_id=@au_id"    connectionstring="server=localhost;database=pubs;integrated security=SSPI" runat="server"></asp:sqldatasource> 

● Cells属性: 通过使用 Cells 属性,可以访问 GridViewRow 对象的单独单元格.
           如果某个单元格包含其他控件,则通过使用单元格的 Controls 集合,可以从单元格检索控件。
           如果某列是BoundField字段,可以使使用Cells[].Text属性。
           【注:在 TemplateField 字段列中可以直接使用数据绑定表达式,无需将值绑定到控件的某个属性。在这种情况下,字段值将自动放置在 DataBoundLiteralControl 控件中。若要检索字段值,必须先从相应单元格检索 DataBoundLiteralControl 控件,然后再使用其 Text 属性。例如:】

<script runat="server">void AuthorsGridView_SelectedIndexChanged(Object sender, EventArgs e)  {    String lastName = selectRow.Cells[1].Text;   // 针对BoundField字段    DataBoundLiteralControl firstNameLiteral = (DataBoundLiteralControl)selectRow.Cells[2].Controls[0];  //针对TemplateField字段    String firstName = firstNameLiteral.Text;}</script><asp:gridview id="AuthorsGridView" datasourceid="AuthorsSqlDataSource"        autogeneratecolumns="false" autogenerateselectbutton="true"        onselectedindexchanged="AuthorsGridView_SelectedIndexChanged"  runat="server">    <columns>      <asp:boundfield datafield="au_lname" headertext="Last Name"/>      <asp:templatefield headertext="FirstName">          <itemtemplate>  <%#Eval("au_fname")%> </itemtemplate>      </asp:templatefield>    </columns></asp:gridview> 

2.4 其它一些属性
        GridViewRow有很多属性,具体可以参考MSDN,
        它包括了一些用于改变样式的属性,这些属性继承自WebControl,
            如: BorderColor,BorderStyle,BackColor,ControlStyle,CssClass,Font,ForColor,Height,Width..
        另外,也有Attributes,Controls,Context,Event,Page,Parent,TemplateControl,ViewState等继承Control的属性 
   2.5 GirdViewRow对象的一些方法
         方法也很多,需要时参考MSDN,常用的,包括:
         FindControl,HasControl,ClearChildControlState…

3. TableCell 对象

TableCell对象表示 Table 控件中的单元格。通过GridViewRow.Cells对象就是返回的TablelCell的集合。
     对于WEB来说,其就是一个<td></td>
     该对象有一些常用的属性,如Text,Controls.RowSpan,ToolTip,VerticalAlign,HorizontalAlign…属性
     关于Control对象,MSDN上有一些说明:
    在 ASP.NET 页上,当以声明方式在服务器控件的开始标记和结束标记之间添加控件时,ASP.NET 会自动将这些控件添加到包含服务器控件的 ControlCollection 中。任何不在服务器上处理的 HTML 标记或者文本字符串都视为 LiteralControl 对象。它们像其他服务器控件一样被添加到集合中。
    Controls 属性允许编程访问任何服务器控件的 ControlCollection 类实例。您可以向集合添加控件、从集合中移除控件,或者循环访问集合中的服务器控件。
Controls.Add(new LiteralControl("<h3>Value: "));

asp.net学习之GridView事件、GridViewRow对象的更多相关文章

  1. asp.net学习之GridView七种字段

    原文:asp.net学习之GridView七种字段 asp.net中GridView绑定到数据源时,可以自动显示数据源的各个字段.只要设定其AutoGenerateColumns为TRUE即可.但这, ...

  2. asp.net学习之扩展GridView

    原文:asp.net学习之扩展GridView 本节讨论如何从现有的控件,进而扩展成强大的,更定制的GridView控件 1.扩展BoundField 默认的BoundField不能显示多文本,文字一 ...

  3. JavaScript学习06 JS事件对象

    JavaScript学习06 JS事件对象 事件对象:当事件发生时,浏览器自动建立该对象,并包含该事件的类型.鼠标坐标等. 事件对象的属性:格式:event.属性. 一些说明: event代表事件的状 ...

  4. ASP.NET本质论第二章应用程序对象学习笔记1

    1.请求的处理参数—上下文对象HttpContext 1) 针对每一次请求,ASP.NET将创建一个处理这次请求所使用的HttpContext对象实例,这个对象实例将用来在ASP.NET服务器的处理过 ...

  5. 从零开始学习jQuery (五) 事件与事件对象

    本系列文章导航 从零开始学习jQuery (五) 事件与事件对象 一.摘要 事件是脚本编程的灵魂. 所以本章内容也是jQuery学习的重点. 本文将对jQuery中的事件处理以及事件对象进行详细的讲解 ...

  6. asp.net学习——Response对象

    (2011-03-29 07:33:03) 转载▼ 标签: 杂谈 分类: asp.net学习 响应的缓冲输出:为了提高服务器的性能,asp.net向浏览器Write的时候默认并不会每Write一次都会 ...

  7. 《纵向切入ASP.NET 3.5控件和组件开发技术》笔记:高效率事件集合对象

    在之前讲的几个例子中,使用的是最普通的定义事件方法,比如KingTextBox中事件是这样定义的:/// <summary>/// 获得本书更多内容,请看:/// http://blog. ...

  8. asp.net学习之DataList控件

    asp.net学习之DataList控件   DataList控件与Repeater控件一样由模板驱动,与Repeater控件不同的是: DataList控件默认输出是一个HTML表格.DataLis ...

  9. asp.net学习之SqlDataSource

    原文:asp.net学习之SqlDataSource 通过 SqlDataSource 控件,可以使用 Web 服务器控件访问位于关系数据库中的数据.其中可以包括 Microsoft SQL Serv ...

随机推荐

  1. SharePoint 2010 新列表模板列表

    SharePoint 2010 新列表模板列表 项目描述叙事 发展环境创造了良好的名单为模板.然后使用列表模板将其复制到生产环境. 脚步 1. 打开"列表设置",找到"将 ...

  2. Oracle GoldenGate (以下简称ogg)在异种移植os同一种db之间的数据同步。

    Oracle GoldenGate (以下简称ogg)在异种移植os同一种db之间的数据同步. ogg要实现的功能: 同步可以细化到单个表,满足特定的where条件rows同步,称号column同步. ...

  3. 采用SharePoint Designer将JavaScript而他们的网站页面集成的定义

    采用SharePoint Designer将JavaScript而他们的网站页面集成的定义 像JavaScript这种动态脚本语言可以给你的页面震撼效果.为了加盟JavaScript要定义自己的网站页 ...

  4. Arrays.asList()

    1.数组--->List String[] ss={"abc","def","xyz","aaaaaaaa",&q ...

  5. async And await异步编程活用基础

    原文:async And await异步编程活用基础 好久没写博客了,时隔5个月,奉上一篇精心准备的文章,希望大家能有所收获,对async 和 await 的理解有更深一层的理解. async 和 a ...

  6. Cocos2d-x场景功能描述的生命周期

    层(Layer)的生命周期函数有例如以下: init().初始化层调用. onEnter().进入层时候调用. onEnterTransitionDidFinish(). 进入层并且过渡动画结束时候调 ...

  7. ServletWeb缓存解决问题

    (1)为什么我们要防止这个问题的浏览器页面缓存: 所以在不须要缓存的页面中须要实现不缓存页面. 代码例如以下: package com.lc.HttpTest; import java.io.IOEx ...

  8. [生产环境数据恢复]innobackupex: fatal error: OR no &#39;datadir&#39; option in group &#39;mysqld&#39; in MySQL options

    1 运行恢复命令  [xxx@xxx-c001db1 tmp]$ time /usr/bin/innobackupex --rsync --user="user" --passwo ...

  9. ubuntu nginx安装及相关linux性能參数优化

    一.安装 下载源代码,解压:tar -xzvf nginx-1.4.7.tar.gz ./configure make && make install 改动默认nginx的监听port ...

  10. MonkeyRunner源代码分析Android通信设备

    正如前面<谁动了我的截图?--Monkeyrunner takeSnapshot方法源代码跟踪分析>所述,本文主要会尝试描写叙述android的自己主动化測试框架MonkeyRunner到 ...