ASP.NET基础 专题
您的位置:csharp > ASP.NET基础专题 > ASP.NET数据绑定
ASP.NET数据绑定
作者:--    发布时间:2019-11-20

每个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.h3.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控件的所选索引的对应值。

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

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


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册