我们经常在cs代码中读取数据源,在html代码中使用<%#DataBinder.Eval(Container.DataItem,"字段名")%>来绑定数据字段,这样有一个缺点,使html代码看起来繁琐. 那么有没有更好的办法来解决这一问题,但又可以实现相同的效果.
记得有一个DataGrid,DataLIst,Repter等控件都有一个 ItemDataBound 事件,在数据元素绑定时触发.那么就应该可以在该事件中绑定html中要显示的字段,但必须在html中加入相应的服务器控件如label,leteral,img等.并应指明其具体的ID
假如有一个DataList控件,要显示的字段在html代码中加入相应的服务器控件,并指明其具体的ID.首先:绑定其数据源如下:
private void Binddl_list(){string sql="select top 10 * from news";SqlConnection myconn=new SqlConnection("server=(local);pwd=;uid=sa;database=1233;pooling=true");SqlCommand mycomm=new SqlCommand (sql,myconn);SqlDataAdapter adpt=new SqlDataAdapter();adpt.selectedCommand=mycomm;DataTable dt=new DataTable ;adpt.Fill (dt);dl_list.DataSource=dt;dl_list.DataBind();}
其次就是在ItemDataBound事件中编写要显示的数据字段
private void dl_list_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e) { if (e.Item.ItemType==ListItemType.AlternatingItem || e.Item.ItemType==ListItemType.Item) { DataRowView view=e.Item.DataItem as DataRowView; //其中 as 为强行转换类型,并注意DataRowView的用法 int spiao=Convert.ToInt32(view["piao"].ToString()); //得到数据库中的相应字段 double slv=spiao/total; Label lb=e.Item.FindControl("lv") as Label; //使用FindControl属性找到DataList中的label控件 lb.Text=slv.ToString(); //给label控件赋值 } }