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

简介: 原文:asp.net学习之GridView事件、GridViewRow对象1. GridView控件的事件     GridView有很多事件,事件可以定制控件的外观或者行为。事件分为三类     1.
原文: asp.net学习之GridView事件、GridViewRow对象

1. GridView控件的事件

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

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

img_1c53668bcee393edac0d7b3b3daff1ae.gif img_405b18b4b6584ae338e0f6ecaf736533.gif 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 控件中之前修改该值

img_1c53668bcee393edac0d7b3b3daff1ae.gif img_405b18b4b6584ae338e0f6ecaf736533.gif Code
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    
if(e.Row.RowType==DataControlRowType.DataRow)
    {
        e.Row.Cells[
2].Text = "<i>" + e.Row.Cells[2].Text + "</i>";
        
// 也可以使用DataBinder.Eval取得相应Cell内的值
       decimal boxOfficeTotal = (decimal)DataBinder.Eval(e.Row.DataItem,”BoxOfficeTotals”);
       
if(boxOfficeTotal > 20000)
           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:如何访问已更新记录的非键字段的原始值

img_1c53668bcee393edac0d7b3b3daff1ae.gif img_405b18b4b6584ae338e0f6ecaf736533.gif 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 事件取消删除操作

img_1c53668bcee393edac0d7b3b3daff1ae.gif img_405b18b4b6584ae338e0f6ecaf736533.gif 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 属性确定用户所选择页面的索引。

img_1c53668bcee393edac0d7b3b3daff1ae.gif img_405b18b4b6584ae338e0f6ecaf736533.gif 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 属性确定正在对哪一列进行排序。如果对地址列进行排序,排序操作将被取消

img_1c53668bcee393edac0d7b3b3daff1ae.gif img_405b18b4b6584ae338e0f6ecaf736533.gif 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 控件中的某个项

img_1c53668bcee393edac0d7b3b3daff1ae.gif img_405b18b4b6584ae338e0f6ecaf736533.gif 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: "));

目录
相关文章
|
2月前
|
SQL 开发框架 前端开发
ASP.NET WEB项目中GridView与Repeater数据绑定控件的用法
ASP.NET WEB项目中GridView与Repeater数据绑定控件的用法
32 0
|
2月前
|
SQL 开发框架 .NET
ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能
ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能
32 0
|
12月前
|
开发框架 .NET
asp.net core过滤器记录响应对象
asp.net core过滤器记录响应对象
67 0
|
开发框架 .NET 数据库连接
在ASP.NET中实现选中、编辑和删除GridView数据项
在ASP.NET中实现选中、编辑和删除GridView数据项
在ASP.NET中实现选中、编辑和删除GridView数据项
|
开发框架 移动开发 前端开发
ASP.NET MVC中使用jQuery Ajax通过FormData对象异步提交图片文件到服务端保存并返回保存的图片路径
ASP.NET MVC中使用jQuery Ajax通过FormData对象异步提交图片文件到服务端保存并返回保存的图片路径
248 0
|
开发框架 前端开发 .NET
|
开发框架 前端开发 .NET
[原创]Asp.net MVC 学习之路-003(增删改查,后端手工,前端生成)
[原创]Asp.net MVC 学习之路-003(增删改查,后端手工,前端生成)
[原创]Asp.net MVC 学习之路-003(增删改查,后端手工,前端生成)
|
开发框架 前端开发 .NET
[原创]Asp.net MVC 学习之路-002
[原创]Asp.net MVC 学习之路-002
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
38 0
|
1月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
95 5