【asp.net】GridView中模板的使用

来源:互联网 发布:java常用设计模式详解 编辑:程序博客网 时间:2024/06/06 02:29

GridView控件的主要用途就是为我们显示数据。但是在GridView中有一些知识是需要我们通过对比去掌握的。

BoundField与TemplateField

在显示绑定的数据中,我们会选择使用这两个控件去显示我们的数据,其中BoundField是简单绑定,它只能显示一个固定的格式,而templateField为模板绑定,对于格式自己可以进行适当的修改。

 

ButtonFieldcommandField

commandField在GridView中使用中只有编辑,更新,删除和选择.而是ButtonField可以自定义方法的(就相当于我们自己在模板中添加一个LinkButon).


下面是一段代码示例.在代码中将这以上两种进行了对比

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="aspnetDemo.GridViewDemo" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title>GridView的数据显示与编辑</title></head><body>    <form id="form1" runat="server">    <div>        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowEditing ="GridView1_RowEditing"   OnRowUpdating="GridView1_RowUpdating1" DataKeyNames="AdminID">            <Columns>                <%--模板绑定,可以对显示的数据添加内容--%>                <asp:TemplateField HeaderText="ID(TemplateField)" HeaderStyle-CssClass="th_category"   >                    <ItemTemplate>                        [ <%# Eval("AdminID") %>]                     </ItemTemplate><HeaderStyle CssClass="th_category"></HeaderStyle>               </asp:TemplateField>               <%-- 简单绑定,只是简单的显示数据--%>           <asp:BoundField DataField="AdminID" HeaderText="ID" />                <asp:BoundField DataField="AdminName" HeaderText="姓名" />           <asp:TemplateField HeaderText="测试" ShowHeader="False">                     <ItemTemplate>                         <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="test" Text="CommandField测试" OnClick="test" ></asp:LinkButton>                     </ItemTemplate>                 </asp:TemplateField>               <asp:CommandField ShowEditButton="True" />                       </columns></asp:GridView></div>    </form></body></html>



显示效果







第一个张图片中第一列使用的是TemplateField绑定(模板绑定),第二行使用了BoundField(简单绑定),可以看到使用模板绑定比简单绑定多了一个“[ ]”.这就是使用模板绑定的好处之一,我们可以对要显示的数据自定义格式,而简单绑定则只是单纯的显示数据。两者并没有好坏之分,需求不同,我们的选择自然也就不同。

第一张图片的第四列和第五列区分了commandField和Butonfield,使用ButtonField,就是在模板中添加一个LinkButton,它只是一个按钮。而第五列则使用的是CommandField。第二张图片显示的是当点击编辑后的效果,可以看到,当点击后使用简单绑定的数据,会变成文本框,同时编辑按钮,会改变成更新、取消按钮,这个就是GridView的数据编辑功能。

0 0