一. 单向数据绑定:
简单来说就是ASP.NET在运行时完成了页面的动态编译,并解析页面的各种服务器端代码,包括数据绑定语法。而数据绑定的语法虽是一些<%# %>代码块,在生成的代码中,仍然使用了服务器端控件以及在DataBinding事件调用DataBinder.Eval方法来完成数据的绑定工作。所有的数据绑定模板控件都使用了这样的机制来进行数据的单向绑定. 这种情况下我们得到的数据不能回发给服务器, 即无法自动完成数据的更新和提交工作.
一般单向数据绑定有下列几种情况(以实例说明):
1. 绑定变量
(1) xhtml
...
<asp:Label ID="Label1" runat="server" Text="<%# Name %>" Font-Names="隶书" ForeColor="Red"></asp:Label></td>
<asp:Label ID="Label2" runat="server" Text="<%# LoginTime %>" Font-Names="隶书" ForeColor="Red"></asp:Label></td>
...
(2) .cs
public partial class _Default : System.Web.UI.Page
{
//此处申明并赋值
public string Name="admin";
public DateTime LoginTime = DateTime.Now;
protected void Page_Load(object sender, EventArgs e)
{
//必须声明整页绑定
Page.DataBind();
}
}
2.绑定集合
(1) xhtml
...
<td align =center >
<asp:DropDownList ID="DropDownList1" runat="server" DataSource =<%# ItemList %> >
</asp:DropDownList></td>
...
(2) .cs
public partial class _Default : System.Web.UI.Page
{
protected ArrayList ItemList = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ItemList.Add("星期一:Monday");
ItemList.Add("星期二:Tuesday");
ItemList.Add("星期三:Wednesday");
ItemList.Add("星期四:Thursday");
ItemList.Add("星期五:Friday");
ItemList.Add("星期六:Saturday");
ItemList.Add("星期日:Sunday");
this.DropDownList1.DataBind();
}
}
}
3.绑定表达式
(1) xhtml
...
<td>求整数1—10的总和及平均数</td>
<td style="width: 203px"> 总和=<%# sum %></td>
<td>平均数=<%# sum/10 %> </td>
</tr>
...
(2) .cs
public partial class _Default : System.Web.UI.Page
{
protected int sum = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
sum = GetSum();
Page.DataBind();
}
protected int GetSum()
{
for (int i = 0; i <= 10; i++)
{
sum += i;
}
return sum;
}
}
4.绑定方法
(1) xhtml
...
<asp:DataList ID="DataList1" runat="server" CellPadding="4" >
<HeaderTemplate >
绑定方法结果
</HeaderTemplate>
<ItemTemplate >
数字:<%# Container.DataItem%>
绝对值为:<%# AbsoluteValue((int)Container.DataItem) %>
</ItemTemplate>
</asp:DataList>
...
(2) .cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ArrayList numbers = new ArrayList();
numbers.Add(8);
numbers.Add(-8);
DataList1.DataSource = numbers;
DataList1.DataBind();
}
}
public int AbsoluteValue(int number)
{
if (number > 0)
return number;
else if (number < 0)
return -number;
else
return 0;
}
}
5. .Eval() 方法进行单向(只读)数据绑定
(1) xhtml
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate >
显示商品信息
<td width ="110" align =center >商品编号</td>
<td width ="110" align =center >商品名称</td>
<td width ="110" align =center >商品说明</td>
<td width ="110" align =center >商品价格</td>
</HeaderTemplate>
<ItemTemplate >
<asp:Label ID ="GoodsID" Text ='<%# Eval("GoodsID") %>' runat =server></asp:Label>
<asp:Label ID ="GoodsName" Text ='<%# Eval("GoodsName") %>' runat =server></asp:Label>
<asp:Label ID ="GoodsIntroduce" Text ='<%#DataBinder.Eval(Container.DataItem,"GoodsIntroduce") %>' runat =server></asp:Label>
<asp:Label ID ="GoodsPrice" Text ='<%#Eval("GoodsPrice","${0}") %>' runat =server></asp:Label>
<asp:Image id="GoodsPhoto"
ImageUrl='<%# Eval("GoodsPhoto") %>' runat="server"/>
</ItemTemplate>
</asp:Repeater>
(2) .cs
public partial class Repeater : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//获得数据库连接
SqlConnection myConn = DBClass.GetConnection();
myConn.Open();
string SqlStr = "select * from tb_GoodsInfo";
SqlDataAdapter da = new SqlDataAdapter(SqlStr, myConn);
//生成DataSet对象并填充数据
DataSet ds = new DataSet();
da.Fill(ds, "GoodsInfo");
//将Repeater控件进行数据绑定
Repeater1.DataSource = ds.Tables["GoodsInfo"].DefaultView;
Repeater1.DataBind();
}
}
public SqlConnection GetConnection()
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection myConn = new SqlConnection(myStr);
return myConn;
}
}
6.将 DropDownList 控件绑定到GridView 控件中
(1) xhtml
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
Font-Size="9pt" ForeColor="#333333" GridLines="None">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="BookID" HeaderText="图书编号ID" />
<asp:BoundField DataField="BookName" HeaderText="图书名" />
<asp:TemplateField HeaderText="销售情况">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSource='<%# ddlbind()%>' DataValueField="SellState"
DataTextField="SellState" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
(2) .cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DropDownList ddl;
if (!IsPostBack)
{
string sqlstr = "select * from tb_SellBook";
SqlConnection myConn = GetConnection();
SqlDataAdapter da = new SqlDataAdapter(sqlstr, myConn);
DataSet ds = new DataSet();
myConn.Open();
da.Fill(ds,"tb_SellBook");
GridView1.DataSource = ds.Tables["tb_SellBook"].DefaultView;
GridView1.DataBind();
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
DataRowView mydrv = ds.Tables["tb_SellBook"].DefaultView[i];
if (Convert.ToString(mydrv["SellState"]).Trim() == "畅销")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
ddl.SelectedIndex = 0;
}
if (Convert.ToString(mydrv["SellState"]).Trim() == "一般")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
ddl.SelectedIndex = 1;
}
if (Convert.ToString(mydrv["SellState"]).Trim() == "滞销")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
ddl.SelectedIndex = 2;
}
}
myConn.Close();
}
}
public SqlConnection GetConnection()
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection myConn = new SqlConnection(myStr);
return myConn;
}
public SqlDataReader ddlbind()
{
string sqlstr = "select distinct SellState from tb_SellBook";
SqlConnection myConn = GetConnection();
SqlCommand myCmd = new SqlCommand(sqlstr, myConn);
myConn.Open();
return myCmd.ExecuteReader();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
DropDownList ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
Response.Write("<Li>" + GridView1.Rows[i].Cells[1].Text + ":" + ddl.SelectedItem.Text + "<br>");
}
}
}
二. 双向数据绑定(可写)
在.NET 2.0中新增了双向的数据绑定方式,主要用在GridView,DetailsView,FormView等数据容器控件中,结合DataSourceControl就可以非常轻松的完成数据的更新和提交工作,而不需要我们手工去遍历输入控件的值。尤其DataSource控件的使用在很大程度上让开发人员工作量大大减少. 虽然有很多时候它促使程序吊不愿意(不用)去了解数据的更新和提交操作内部工作原理, 致使很多 "有志青年" 十分抵触它. 但是我需要说的是, 如果你了解了它的工作原理, 运行机制, 然后再使用它是不是会大大提高我们的开发效率呢?
ASP.NET在模板中双向绑定字段,是通过<%# Bind() %>这样的语法实现.如下:
<asp:DetailsDataSouce ID="DetailsDataSouce1" runat="server"> </asp:DetailsDataSouce>
<asp:DetailsView ID="detailsView" runat="server" DefaultMode="Edit" DataSourceID="DetailsDataSouce1">
<Fields>
<asp:TemplateField>
<HeaderTemplate>
姓名:
</HeaderTemplate>
<EditItemTemplate>
<asp:TextBox ID="textBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderTemplate>
性别:
</HeaderTemplate>
<EditItemTemplate>
<asp:TextBox ID="textBox1" runat="server" Text='<%# Bind("gender") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>