ASP.Net之数据绑定

时间:2023-03-05 09:10:50

---恢复内容开始---

【概述】数据绑定是指从数据源获取数据或向数据源写入数据。简单的数据绑定可以是对变量或属性的绑定,比较复杂的是对ASP.NET数据绑定控件的操作

1、简单的属性绑定

基于属性的数据绑定所涉及的属性必须包含在get访问器,因为在数据绑定的过程中,数据显示控件需要通过属性的get访问器从属性中读取数据。语法:<%#属性名称%>


例:简单的数据绑定

1、在网站的cs文件中添加两个用于数据绑定的公共方法

 public string GoodsName
{
get
{
return "彩色电视机";
}
}
public string GoodsKind
{
get
{
return "家用电器";
}
}

2、设定完数据绑定的数据源,既可以与其显示控件建立绑定关系。

body>
<form id="form1" runat="server">
<div>
<h1>简单的数据绑定</h1><hr />
<asp:Label ID="Label1" runat="server" Text='<%# str %>'></asp:Label><hr />
<h2>商品名称:<%#GooodsName %></h2><hr />
<h2>公司名称:<%#GoodsKind %></h2><hr /> </div>
</form>
</body>

3、在page_Load中设置

        protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind(); }

ASP.Net之数据绑定


【表达式绑定】

将数据绑定到要显示的控件之前,通常需要对数据进行处理,也就是说,需要使用表达式做简单的处理后,再将执行结果绑定到显示控件上。

例:表达式绑定

 <p>
<asp:Label ID="Label4" runat="server" Text='<%#"总金额为:"+Convert.ToString(Convert.ToDecimal(TextBox1.Text)*Convert.ToInt32(TextBox2.Text)) %>'></asp:Label>
</p>

【四】集合绑定

有一些服务器控件是多记录控件,这类控件即可使用集合作为数据源对其进行绑定。通常情况下,集合数据源主要包括Arraylist、Hashabel、DataView、DataReader等。

例:以ArrayList集合绑定DropDownlist控件作为实例进行具体的介绍:

  protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
//橡树足迹和添加数据
System.Collections.ArrayList arraylist = new System.Collections.ArrayList();//定义聚合数组,作为数据源
arraylist.Add("香蕉");//向数组中添加数据
arraylist.Add("苹果");
arraylist.Add("西瓜");
arraylist.Add("西红柿");
DropDownList1.DataSource = arraylist;//实现数据绑定
DropDownList1.DataBind();//调用dataBind方法进行数据绑定 }

ASP.Net之数据绑定


【五】方法调用结果绑定

定义一个方法,其中可以定义表达式计算的几种方式,在数据绑定表达式中通过传递不同的参数得到调用方法的结果。

例:如何将方法的返回值绑定到显示控件属性上。

 <div>
绑定方法调用的结果<br />
第一个数:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
第二个数:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
运算符号:<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList><br />
<asp:Button ID="Button1" runat="server" Text="提交" /><br />
<asp:Label ID="Label3" runat="server" Text='<%#operation(ddlOperator.SelectedValue )%>'></asp:Label>
</div>
  //定义一个用于方法调用的方法
public string operation(string VarOperator)
{
double num1 = Convert.ToDouble(TextBox2.Text);
double num2 = Convert.ToDouble(TextBox3.Text);
double result = ;
switch (VarOperator)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
return result.ToString();
}

  

---恢复内容结束---