最近做一个Repeater的2层嵌套,使用List做数据源来取代Datatable绑定,但是使用原来的代码,却一直出现问题,怪我原来没注意,没深入研究,关键时候基础真重要呀!
常见的三种数据源以及其e.Item.DataItem的转换方法:
//使用DataSet和DataTable绑定数据源时
DataRowView view = (DataRowView)e.Item.DataItem;
//DataReader绑定数据源时
System.Data.Common.DbDataRecord view = (System.Data.Common.DbDataRecord)e.Item.DataItem;
//使用泛型做数据源时,则是泛型对应的类型。
//例如 IList<DocumentInfo> 为数据源
DocumentInfo docInfo = (DocumentInfo)e.Item.DataItem;
附上我的代码,供大家参考。
protected void rptPrescription_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//找到里层的Repeater对象
Repeater rpt = (Repeater)e.Item.FindControl("rptMedicine");
//找到父级Repeater关联的数据项
//System.Data.DataRowView rowv = (System.Data.DataRowView)e.Item.DataItem;
//提取分类ID
//int PrescriptionId = Convert.ToInt32(rowv["PrescriptionId"]);
//并绑定药品Repeater
//rpt.DataSource = (List<Model.PrescriptionDetail>)rowv["PrescriptionDetails"];
Model.Prescription prescriptionModel = (Model.Prescription)e.Item.DataItem;
rpt.DataSource = prescriptionModel.PrescriptionDetails;
rpt.DataBind();
}
}