• ASP.NET GridView


    本文内容

    • 分页并排序
    • CommandField
    • HyperLinkField和ButtonField
    • 模板列TemplateField
    • 用途多多的 OnRowDataBound 事件

    分页并排序

    <%@ Page Language="C#" %>
     
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Web.UI" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         protected void Page_Load(object sender, EventArgs e)
       3:         {
       4:             if (!IsPostBack)
       5:             {
       6:                 ViewState["Orderby"] = "c1";
       7:                 ViewState["Sort"] = "ASC";
       8:                 this.Bind();
       9:             }
      10:         }
      11:         private void Bind()
      12:         {
      13:             DataTable dt = this.CreateDataSource();
      14:             DataView dv = dt.DefaultView;
      15:             string Orderby = (string)ViewState["Orderby"] + " " + (string)ViewState["Sort"];
      16:             dv.Sort = Orderby;
      17:             GridView1.DataSource = dv;
      18:             GridView1.DataKeyNames = new string[] { "c1" };
      19:             GridView1.DataBind();
      20:         }
      21:         private DataTable CreateDataSource()
      22:         {
      23:             DataTable dt = new DataTable();
      24:             dt.Columns.Add("c1", typeof(int));
      25:             dt.Columns.Add("c2", typeof(string));
      26:             dt.Columns.Add("c3", typeof(string));
      27:             for (int i = 0; i < 100; i++)
      28:             {
      29:                 DataRow dr = dt.NewRow();
      30:                 dr[0] = i;
      31:                 dr[1] = i;
      32:                 dr[2] = i;
      33:                 dt.Rows.Add(dr);
      34:             }
      35:             return dt;
      36:         }
      37:         protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
      38:         {
      39:             GridView1.PageIndex = e.NewPageIndex;
      40:             this.Bind();
      41:         }
      42:         protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
      43:         {
      44:             string Orderby = e.SortExpression;
      45:             if (ViewState["Orderby"].ToString() == Orderby)
      46:             {
      47:                 if (ViewState["Sort"].ToString() == "Desc")
      48:                     ViewState["Sort"] = "ASC";
      49:                 else
      50:                     ViewState["Sort"] = "Desc";
      51:             }
      52:             else
      53:             {
      54:                 ViewState["Orderby"] = e.SortExpression;
      55:             }
      56:             this.Bind();
      57:         }
      58:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" OnSorting="GridView1_Sorting" AllowSorting="True"
            OnPageIndexChanging="GridView1_PageIndexChanging" AutoGenerateColumns="False"
            AllowPaging="True">
            <Columns>
                <asp:BoundField DataField="c1" HeaderText="列1" SortExpression="c1" />
                <asp:BoundField DataField="c2" HeaderText="列2" SortExpression="c2" />
                <asp:BoundField DataField="c3" HeaderText="列3" SortExpression="c3" />
            </Columns>
        </asp:GridView>
        </form>
    </body>
    </html>
    说明
    • 针对分页部分

    (1) 在 Page_Load 事件里设置 GridView 的“分页(AllowPaging)”、“每页记录条数(PageSize)”、“自动产生列(AutoGenerateColumns)”属性,这些属性也可以直接在控件里设置;
    (2) 然后从数据库中获得数据集,并设置主键,再绑定到控件;
    (3) 主键可以不设置,设置主键主要是为了便于在 GridView 控件中利用主键直接定位到某条记录,如:GridView1.DataKeys[e.RowIndex].Value,对该记录进行编辑、修改和删除操作;
    (4) 如果不设置主键,也可以从 GridView 单元格里直接获取数据 GridView1.Rows[i].Cells[i].toString(),如果 GridView 控件处于编辑状态,要将其转换成相应的控件类型;
    (5) 默认情况下,处于编辑状态的 GridView 控件,每个单元格是 TextBox 控件。如果使用模板列,自定义每个单元格的控件,如单选框或复选框,则要进行相应的转换;
    (6) 一般,若想获得某条记录某列的值,是通过模板列中控件的ID在 GridView 控件里进行查找,例如:

    (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); 

    含义:在 GridView 控件的第 i 行上,查找“ID”为“CheckBox1”的控件,并转换成 CheckBox 类型,这样就可以对这个单元格进行形如 CheckBox 控件的操作。
    另外,无论何时你都可以遍历 GridView 的标题和网格内容。如下代码遍历 GridView 的标题:

    for (int i = 0; i <= GridView1.HeaderRow.Cells.Count - 1; i++)  
    {  
        string str = GridView1.HeaderRow.Cells[i].Text;  
        // ......  
    } 

    如下代码遍历 GridView 的内容:

    for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
    {  
        for (int j = 1; j <= GridView1.HeaderRow.Cells.Count - 1; j++)  
        {  
            string str = GridView1.Rows[i].Cells[j].Text;  
            // ......  
        }  
    }  

    (7) 对于数据分页,一般不采用ASP.NET自带的,比较难看,而是采用专门的分页控件。分页控件有各种式样,其实原理都一样,将SQL语句、当前页数和总页数保存到页面变量中,根据需要在页面上Render画出来。

    • 针对排序部分

    (1) 设置GridView控件的AutoGenerateColumns(是否自动产生列)和AllowSorting(是否允许排序)属性;

    (2) 在GridView控件里用BoundField自定义绑定列(字段),并设置其属性DataField、HeaderText和SortExpression设置绑定列名、显示列名和排序字段;

    (3) 在Page_Load事件里设置默认的排序字段和排序方式,绑定到控件;

    (4) 实现排序功能必须使用数据集的视图。在自定义绑定函数Bind()中,使用DataTable数据集的视图DefaultView绑定控件,从页面的视图变量Sort和Order中获得当前的排序字段和排序方式,赋值给数据集视图DefaultView的成员变量Sort,绑定到控件;

    (5) 最后,在GridView1_Sorting事件中,用e.SortExpression获得当前的排序字段,并根据实际改变排序字段和排序方式,绑定到控件。

    CommandField

    <%@ Page Language="C#" %>
     
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Web.UI" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:        protected void Page_Load(object sender, EventArgs e)
       3:        {
       4:            if (!IsPostBack)
       5:            {
       6:                 this.Bind();
       7:            }
       8:        }
       9:        private void Bind()
      10:        {
      11:            DataTable dt = this.CreateDataSource();
      12:            GridView1.DataSource = dt;
      13:            GridView1.DataKeyNames = new string[] { "c1" };
      14:            GridView1.DataBind();
      15:        }
      16:        private DataTable CreateDataSource()
      17:        {
      18:            DataTable dt = new DataTable();
      19:            dt.Columns.Add("c1", typeof(int));
      20:            dt.Columns.Add("c2", typeof(string));
      21:            dt.Columns.Add("c3", typeof(string));
      22:            for (int i = 1; i <= 100; i++)
      23:            {
      24:                 DataRow dr = dt.NewRow();
      25:                 dr[0] = i;
      26:                 dr[1] = i * 10;
      27:                 dr[2] = i * 100;
      28:                 dt.Rows.Add(dr);
      29:            }
      30:            return dt;
      31:        }
      32:        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
      33:        {
      34:            GridView1.PageIndex = e.NewPageIndex;
      35:            this.Bind();
      36:        }
      37:        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
      38:        {
      39:            GridView1.EditIndex = e.NewEditIndex;
      40:            Bind();
      41:        }
      42:        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
      43:        {
      44:            string sqlStr = "DELETE FROM RECORDNOWRAP WHERE c1=:var";
      45:            string keyValue = GridView1.DataKeys[e.RowIndex].Value.ToString();
      46:            sqlStr = sqlStr.Replace(":var", keyValue);
      47:            // 执行数据删除
      48:            this.TextBox1.Text = "已删除主键为 " +keyValue + " 的记录.";
      49:            Bind();
      50:        }
      51:        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
      52:        {
      53:            GridView1.EditIndex = -1;
      54:            Bind();
      55:        }
      56:        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
      57:        {
      58:            string sqlStr = "UPDATE RECORDNOWRAP SETc1=:var1,c2=':var2',c3=':var3' WHERE c1=:vKeyValue";
      59:            string keyValue = GridView1.DataKeys[e.RowIndex].Value.ToString();
      60:            string var1 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim();
      61:            string var2 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim();
      62:            string var3 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim();
      63:            sqlStr = sqlStr.Replace(":var1", var1).Replace(":var2",var2).Replace(":var3", var3).Replace(":vKeyValue",keyValue);
      64:            // 执行数据库更新
      65:            this.TextBox1.Text = "已更新主键为 " +keyValue + " 的记录.";
      66:            
      67:            GridView1.EditIndex = -1;
      68:            Bind();
      69:        }
      70:        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
      71:        {
      72:            int index = GridView1.SelectedIndex;
      73:            TextBox1.Text =GridView1.DataKeys[index].Value.ToString();
      74:        }
      75:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
            OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"
            OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
            OnPageIndexChanging="GridView1_PageIndexChanging">
            <Columns>
                <asp:CommandField HeaderText="选择" ShowSelectButton="True" SelectText="选择" />
                <asp:CommandField HeaderText="编辑" ShowEditButton="True" SelectText="select" CancelText="取消"
                    EditText="编辑" UpdateText="更新" />
                <asp:CommandField HeaderText="删除" ShowDeleteButton="True" SelectText="select" DeleteText="删除" />
                <asp:BoundField DataField="c1" HeaderText="列1" />
                <asp:BoundField DataField="c2" HeaderText="列2" />
                <asp:BoundField DataField="c3" HeaderText="列3" />
            </Columns>
        </asp:GridView>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        </form>
    </body>
    </html>
    说明

    1,在 Bind() 函数里,设置主键,可以为多个。这样才能在以后使用GridView1.DataKeys[...].Value。

    HyperLinkField和ButtonField

    <%@ Page Language="C#" %>
     
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Web.UI" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         protected void Page_Load(object sender, EventArgs e)
       3:         {
       4:             if (!IsPostBack)
       5:             {
       6:                 this.Bind();
       7:             }
       8:         }
       9:         private void Bind()
      10:         {
      11:             DataTable dt = this.CreateDataSource();
      12:             GridView1.DataSource = dt;
      13:             GridView1.DataKeyNames = new string[] { "c1" };
      14:             GridView1.DataBind();
      15:         }
      16:         private DataTable CreateDataSource()
      17:         {
      18:             DataTable dt = new DataTable();
      19:             dt.Columns.Add("c1", typeof(int));
      20:             dt.Columns.Add("c2", typeof(string));
      21:             dt.Columns.Add("c3", typeof(string));
      22:             for (int i = 1; i <= 100; i++)
      23:             {
      24:                 DataRow dr = dt.NewRow();
      25:                 dr[0] = i;
      26:                 dr[1] = i * 10;
      27:                 dr[2] = i * 100;
      28:                 dt.Rows.Add(dr);
      29:             }
      30:             return dt;
      31:         }
      32:         protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
      33:         {
      34:             GridView1.PageIndex = e.NewPageIndex;
      35:             this.Bind();
      36:         }
      37:         protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
      38:         {
      39:             if (e.CommandName == "select")
      40:             {
      41:                 int i = Convert.ToInt32(e.CommandArgument);
      42:                 TextBox1.Text = GridView1.Rows[i].Cells[2].Text.ToString();
      43:             }
      44:         } 
      45:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
            OnRowCommand="GridView1_RowCommand" OnPageIndexChanging="GridView1_PageIndexChanging">
            <Columns>
                <asp:ButtonField CommandName="select" HeaderText="一般按钮" Text="选择" ButtonType="Button"
                    DataTextField="c1" DataTextFormatString="选择:{0}"></asp:ButtonField>
                <asp:HyperLinkField HeaderText="链接按钮" Text="选择" DataTextField="c1" DataTextFormatString="选择:{0}"
                    DataNavigateUrlFields="c1" DataNavigateUrlFormatString="~/page.aspx?id={0}">
                </asp:HyperLinkField>
                <asp:BoundField DataField="c1" HeaderText="列1" />
                <asp:BoundField DataField="c2" HeaderText="列2" />
                <asp:BoundField DataField="c3" HeaderText="列3" />
            </Columns>
        </asp:GridView>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        </form>
    </body>
    </html>
    说明
    • 针对ButtonField

    (1) 创建两个事件OnPageIndexChanging 和 OnRowCommand;

    (2) GridView控件的第一列是Button自定义控件,CommandName="select"命令名为选择,ButtonType="Button"按钮类型为按钮,此外还有 LinkButton 和 ImageButton 类型,DataTextField="empno" 和DataTextFormatString="选择:{0}" 设置绑定的字段和显示格式;

    (3) Convert.ToInt32(e.CommandArgument) 获得行号。

    • 针对HyperLinkField

    (1) 设置 DataNavigateUrlFields="c1"和DataNavigateUrlFormatString="~/page.aspx?id={0}",将编号作为参数,传给page.aspx页面。

    模板列TemplateField

    <%@ Page Language="C#" %>
     
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Web.UI" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         protected void Page_Load(object sender, EventArgs e)
       3:         {
       4:             if (!IsPostBack)
       5:             {
       6:                 this.Bind();
       7:             }
       8:         }
       9:         private void Bind()
      10:         {
      11:             DataTable dt = this.CreateDataSource();
      12:             GridView1.DataSource = dt;
      13:             GridView1.DataKeyNames = new string[] { "id" };
      14:             GridView1.DataBind();
      15:         }
      16:         private DataTable CreateDataSource()
      17:         {
      18:             DataTable dt = new DataTable("info");
      19:             dt.Columns.Add("id", typeof(int));
      20:             dt.Columns.Add("name", typeof(string));
      21:             dt.Columns.Add("sex", typeof(int));
      22:             dt.Columns.Add("edu", typeof(int));
      23:             for (int i = 1; i <= 100; i++)
      24:             {
      25:                 DataRow dr = dt.NewRow();
      26:                 dr[0] = 1000 + i;
      27:                 dr[1] = "名字" + i;
      28:                 dr[2] = (i % 2).ToString();
      29:                 dr[3] = ((i % 3) + 1).ToString();
      30:                 dt.Rows.Add(dr);
      31:             }
      32:             return dt;
      33:         }
      34:         protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
      35:         {
      36:             GridView1.EditIndex = e.NewEditIndex;
      37:             Bind();
      38:         }
      39:         protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
      40:         {
      41:             GridView1.EditIndex = -1;
      42:             Bind();
      43:         }
      44:         protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
      45:         {
      46:             string sqlStr = "DELETE FROM info WHERE id=':vId'";
      47:             string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
      48:             sqlStr = sqlStr.Replace(":vId", id);
      49:             // 执行数据库删除
      50:             this.TextBox1.Text = "已执行删除.";
      51:             Bind();
      52:         }
      53:         protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
      54:         {
      55:             string sqlStr = "update info set sex=':vSex',name=':vName',edu=':vEdu' where id=:vId'";
      56:             string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
      57:             string name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_name")).Text.ToString().Trim();
      58:             string sex = ((RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("rbl_sex")).SelectedValue.Trim();
      59:             string edu = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddl_edu")).SelectedItem.Text.ToString();
      60:             sqlStr = sqlStr.Replace(":vSex", sex).Replace(":vName", name).Replace(":vEdu", edu).Replace(":vId", id);
      61:             // 执行数据库更新
      62:             GridView1.EditIndex = -1;
      63:             Bind();
      64:         }
      65:         protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
      66:         {
      67:             GridView1.PageIndex = e.NewPageIndex;
      68:             this.Bind();
      69:         }
      70:         protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
      71:         {
      72:             if (e.Row.RowType == DataControlRowType.DataRow)
      73:             {
      74:                 Label lbl = ((Label)e.Row.FindControl("lbl_edu"));
      75:                 if (lbl != null)
      76:                 {
      77:                     switch (lbl.Text)
      78:                     {
      79:                         case "1":
      80:                             lbl.Text = "学士";
      81:                             break;
      82:                         case "2":
      83:                             lbl.Text = "硕士";
      84:                             break;
      85:                         case "3":
      86:                             lbl.Text = "博士";
      87:                             break;
      88:                     }
      89:                 }
      90:                 lbl = ((Label)e.Row.FindControl("lbl_sex"));
      91:                 if (lbl != null)
      92:                 {
      93:                     switch (lbl.Text)
      94:                     {
      95:                         case "1":
      96:                             lbl.Text = "男";
      97:                             break;
      98:                         case "0":
      99:                             lbl.Text = "女";
     100:                             break;
     101:                     }
     102:                 }
     103:                 DropDownList ddl = (DropDownList)e.Row.FindControl("ddl_edu");
     104:                 if (ddl != null)
     105:                 {
     106:                     ddl.Items.Clear();
     107:                     ddl.Items.Add(new ListItem("学士", "1"));
     108:                     ddl.Items.Add(new ListItem("硕士", "2"));
     109:                     ddl.Items.Add(new ListItem("博士", "3"));
     110:                 }
     111:                 RadioButtonList rbl = (RadioButtonList)e.Row.FindControl("rbl_sex");
     112:                 if (rbl != null)
     113:                 {
     114:                     rbl.Items.Clear();
     115:                     rbl.Items.Add(new ListItem("男", "1"));
     116:                     rbl.Items.Add(new ListItem("女", "0"));
     117:                     string selectedValue = rbl.DataValueField.ToString();
     118:                     switch (selectedValue)
     119:                     {
     120:                         case "1":
     121:                             rbl.Items[0].Selected = true;
     122:                             break;
     123:                         case "0":
     124:                             rbl.Items[1].Selected = true;
     125:                             break;
     126:                     }
     127:                 }
     128:             }
     129:         }  
     130:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true"
            OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound"
            OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"
            OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
            <Columns>
                <asp:TemplateField HeaderText="编号">
                    <ItemTemplate>
                        <%
       1: # this.GridView1.PageIndex * this.GridView1.PageSize + this.GridView1.Rows.Count + 1
    %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="学号">
                    <ItemTemplate>
                        <asp:Label ID="lbl_id" runat="server" Text='<%# Bind("id")%>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_id" runat="server" Text='<%# Bind("id")%>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="名字">
                    <ItemTemplate>
                        <asp:Label ID="lbl_name" runat="server" Text='<%# Bind("name")%>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_name" runat="server" Text='<%# Bind("name")%>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="性别">
                    <ItemTemplate>
                        <asp:Label ID="lbl_sex" runat="server" Text='<%# Bind("sex")%>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:RadioButtonList ID="rbl_sex" runat="server" DataValueField='<%# Bind("sex")%>'>
                        </asp:RadioButtonList>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="学历">
                    <ItemTemplate>
                        <asp:Label ID="lbl_edu" runat="server" Text='<%# Bind("edu")%>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddl_edu" runat="server" DataValueField='<%# Bind("edu")%>'>
                        </asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="操作" ShowHeader="False">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                            Text="编辑" OnClientClick="return confirm('确认要编辑吗?');">  
                        </asp:LinkButton>
                        <asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="Delete"
                            Text="删除" OnClientClick="return confirm('确认要删除吗?');">  
                        </asp:LinkButton>
                        <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Select"
                            Text="选择"></asp:LinkButton>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                            Text="更新"></asp:LinkButton>
                        <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                            Text="取消"></asp:LinkButton>
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        </form>
    </body>
    </html>

    用途多多的 OnRowDataBound 事件

    <%@ Page Language="C#" %>
     
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Web.UI" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         protected void Page_Load(object sender, EventArgs e)
       3:         {
       4:             if (!IsPostBack)
       5:             {
       6:                 this.Bind();
       7:             }
       8:         }
       9:         private void Bind()
      10:         {
      11:             DataTable dt = this.CreateDataSource();
      12:             GridView1.DataSource = dt;
      13:             GridView1.DataKeyNames = new string[] { "c1" };
      14:             GridView1.DataBind();
      15:         }
      16:         private DataTable CreateDataSource()
      17:         {
      18:             DataTable dt = new DataTable();
      19:             dt.Columns.Add("c1", typeof(int));
      20:             dt.Columns.Add("c2", typeof(string));
      21:             dt.Columns.Add("c3", typeof(string));
      22:             for (int i = 0; i < 100; i++)
      23:             {
      24:                 DataRow dr = dt.NewRow();
      25:                 dr[0] = i;
      26:                 dr[1] = i;
      27:                 dr[2] = i;
      28:                 dt.Rows.Add(dr);
      29:             }
      30:             return dt;
      31:         }
      32:         protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
      33:         {
      34:             GridView1.PageIndex = e.NewPageIndex;
      35:             this.Bind();
      36:         }
      37:         protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
      38:         {
      39:             if (e.Row.RowIndex != -1)
      40:             {
      41:                 if (e.Row.RowIndex % 2 == 0)
      42:                 {
      43:                     e.Row.BackColor = System.Drawing.Color.Red;
      44:                     e.Row.Cells[0].BackColor = System.Drawing.Color.Chocolate;
      45:                 }
      46:                 else
      47:                 {
      48:                     e.Row.BackColor = System.Drawing.Color.Blue;
      49:                     e.Row.Cells[0].BackColor = System.Drawing.Color.Coral;
      50:                 }
      51:             }
      52:         }
      53:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" OnPageIndexChanging="GridView1_PageIndexChanging"
            AutoGenerateColumns="False" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:BoundField DataField="c1" HeaderText="列1" SortExpression="c1" />
                <asp:BoundField DataField="c2" HeaderText="列2" SortExpression="c2" />
                <asp:BoundField DataField="c3" HeaderText="列3" SortExpression="c3" />
            </Columns>
        </asp:GridView>
        </form>
    </body>
    </html>
    说明

    (1) OnRowDataBound 事件是数据绑定后,显示之前触发,此事件通常用于改变数据库中显示在GridView中的内容。在本例中,改变奇数行和偶数行的背景色,顺便改变奇数行和偶数行第一列的背景色;

    (2) 根据这个事件的描述,我们可以想到,这个事件有很多用处。

    比如,突出显示某列(某行)。假设有个员工工资的数据,想突出显示员工工资大于1000的员工;

    比如,截取长字符串。假设数据中某行某列的数据很长,造成显示问题,那么可以截取该数据一部分来显示,如字符长度大于某个值之后的所有字符用省略号代替;

    比如,改变选中行的风格。也就是说,当选中某行数据时(鼠标停留时),会高亮显示该数据行。代码如下:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FF0033'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        }
    }

    注意:在 OnRowDataBound 事件中,添加客户端事件 onmouseover 和 onmouseout ,改变行背景色。

    比如,超长记录不换行。假设数据的字段很多,并且某个字段的数据很长,超过屏幕宽度,但是还想全部显示,又不想截取。

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Wrap = false;
            e.Row.Cells[0].Style.Add("word-break", "keep-all");  
        }
    }

    注意:e.Row.Cells[0]中的索引表示那个数据很长的字段。通过上面两段代码可以看到,在服务器端,可以向控件添加客户端功能,比如CSS,事件等,慢慢挖掘吧。

    另外,其实,像这样,在后台改变网格的CSS,意义不是很大,因为这是UI人员的工作,而不是开发人员的,UI们能把效果做得更好。就像我刚毕业时做的一个项目,每张表的数据字段都很多,几乎超过100个,个别字段还有大段的文字描述。当时我想,让网格在页面的一个DIV区域内显示。如果超过屏幕区域,就自动出滚动条。如果个别字段数据很长,那也不截取,不换行显示。让网格始终在一个区域内显示,无论字段多少,数据多长。头也催,要做成这种效果。搞了半天也没弄出来。我当时就不爽了,开发量那么大,就那么几个鸟人,你还让我给你做界面……后来公司新来个做UI,我说了下需求,人家很快搞定,全是CSS。

    下载 Demo

  • 相关阅读:
    关于scanf、getchar、getch、getche缓冲区分析——C语言
    堆排序(大顶堆、小顶堆)----C语言
    预处理命令使用详解----#if、#endif、#undef、#ifdef、#else、#elif
    参数传递---关于数组的退化
    控制台API函数----HANDLE、SetConsoleCursorPosition、SetConsoleTextAttribute
    二叉树的遍历(前序、中序、后序、已知前中序求后序、已知中后序求前序)
    Fiddler 插件开发,使用 WPF 作为 UI 控件
    从程序集加载类型,遇到 ReflectionTypeLoadException 的处理办法
    如何将应用程序与文件类型(文件扩展名)关联起来?
    为什么 WPF 的 Main 方法需要标记 STAThread 。
  • 原文地址:https://www.cnblogs.com/liuning8023/p/2145175.html
Copyright © 2020-2023  润新知