GridView.RowDataBound 事件

定义

GridView 控件中将数据行绑定到数据时发生。

public event System.Web.UI.WebControls.GridViewRowEventHandler RowDataBound;

事件类型

示例

本主题附带了一个包含源代码的 Visual Studio 网站项目: 下载

以下示例演示如何使用 RowDataBound 事件修改数据源中字段的值,然后再将其显示在控件中 GridView


<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {
        
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Display the company name in italics.
      e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
        
    }
    
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView RowDataBound Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView RowDataBound Example</h3>

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        allowpaging="true"
        onrowdatabound="CustomersGridView_RowDataBound" 
        runat="server">
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSqlDataSource"  
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        runat="server">
      </asp:sqldatasource>
            
            
    </form>
  </body>
</html>

注解

必须先 GridView 将控件中的每个行绑定到数据源中的记录,然后才能呈现控件。 RowDataBound当对象表示GridViewRow的数据行 () 绑定到控件中的数据时,将引发 该GridView事件。 这使你能够提供一个事件处理方法,该方法执行自定义例程,例如,每当发生此事件时,修改绑定到行的数据的值。

对象 GridViewRowEventArgs 将传递给事件处理方法,该方法使你能够访问所绑定行的属性。 若要访问行中的特定单元格,请使用 Cells 对象的 属性 GridViewRow 中包含的 Row 对象的 属性 GridViewRowEventArgs 。 可以使用 属性确定) 绑定 (标题行、数据行等的行 RowType 类型。

有关如何处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

另请参阅