不带数据绑定表达式的数据绑定
为什么要避免使用数据表达式呢?使用数据表达式并不会出错,而且只你想用就可以一直使用数据绑定表达式,但是,你会发现当需要在模板内执行复杂的操作时,不使用数据绑定表达式能提高代码的可读性。
不使用数据表达式的窍门是处理控件的ItemDataBound事件(Repeater、DataGrid、DataList都有ItemDataBound事件)。ItemDataBound事件为从数据源检索出的每一个项所触发。因此,如果绑定Repeater控件到包含11个作者的数据库表,那么ItemDataBound事件就被触发11次——每个作者触发一次。
除了ItemDataBound外,Repeater控件也支持ItemCreated事件。ItemCreate事件是创建每个RepeaterItem时触发。DataGrid与DataList也有ItemCreate事件。
例子:
页面代码:
……
……
<asp:repeater id="Repeater2" runat="server">
<ItemTemplate>
<asp:Label ID="lblItem" runat="server" />
</ItemTemplate>
</asp:repeater>
……
……后台代码:
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection conn =new SqlConnection("server=(local);database=JgyeyMIB;pwd=;uid=sa");
SqlCommand cmd = new SqlCommand("Select * from ClassTB select * from ClassTB",conn);
conn.Open();
SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
this.Repeater2.DataSource = rd;
this.Repeater2.DataBind();
rd.Close();
}
![](/Images/OutliningIndicators/None.gif)
private void Repeater2_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item)
{
Label lbl = new Label();
lbl = e.Item.FindControl("lblItem") as Label;
lbl.Text = DataBinder.Eval(e.Item.DataItem,"className","{0}")+"<br>";
}
}
![](/Images/OutliningIndicators/None.gif)
不使用数据表达式的窍门是处理控件的ItemDataBound事件(Repeater、DataGrid、DataList都有ItemDataBound事件)。ItemDataBound事件为从数据源检索出的每一个项所触发。因此,如果绑定Repeater控件到包含11个作者的数据库表,那么ItemDataBound事件就被触发11次——每个作者触发一次。
除了ItemDataBound外,Repeater控件也支持ItemCreated事件。ItemCreate事件是创建每个RepeaterItem时触发。DataGrid与DataList也有ItemCreate事件。
例子:
页面代码:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)