这两天因为网站上有一个子父类别的显示。在编写的时候遇到一些问题,把它记录下来,以供参考:
前端:
<asp:Repeater ID="RepProTypeParent" runat="server" OnItemDataBound="ProType_itemDataBound">
<ItemTemplate>
<div class="h_div">
<h3 class="font14"><a href="/Supply/Trade-<%#Eval("id")%>.aspx"><%#Eval("type")%></a></h3>
<asp:Repeater ID="RepProTypeChild" runat="server"><HeaderTemplate><div class="h_div1"></HeaderTemplate><ItemTemplate>
<a href="/Supply/Trade-<%#Eval("id")%>.aspx"><%#Eval("type")%></a></ItemTemplate><FooterTemplate></div></FooterTemplate></asp:Repeater>
</div></ItemTemplate></asp:Repeater>
后台主要代码:
protected DataTable newTable=new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// proTypeTable 放在此读取数据为了减少从数据库读写数据的次数,达到优化的目的
proTypeTable = newsInfo.GetDataTable("select id,type,SuperiorsID from w_industryType where SuperiorsID<>0");
newTable = proTypeTable.Clone();
BindParent();
}
}//绑定父类
protected void BindParent(){
proTypeTables = newsInfo.GetDataTable("select id,type from industryType where SuperiorsID=0");
RepProTypeParent.DataSource = proTypeTables;
RepProTypeParent.DataBind();
}
/// <summary>
/// 绑定子类
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ProType_itemDataBound(object sender, RepeaterItemEventArgs e)
{
newTable=proTypeTable.clone();
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
Repeater RepChild = e.Item.FindControl("RepProTypeChild") as Repeater;
DataRowView getRow = (DataRowView)e.Item.DataItem;
DataRow[] drs=proTypeTable.Select("SuperiorsID="+getRow["id"]);
Response.Write(getRow["id"].ToString()+"-");
foreach(DataRow dr in drs){
newTable.ImportRow(dr);
} newTable.AcceptChanges();
RepChild.DataSource =newTable;
RepChild.DataBind();
newTable.Clear();
}
}
遇到的问题:
在子控件RepProTypeChild的DataBound事件绑定中,刚开始验证了等于item类型的绑定。测试发现item只能绑定到单数的行。加入 了AlternatingItem才正常。经查询:
ListItemType.Item:单数行
AlternatingItem:双数行
两个必须同时使用才能验证Repeater 所有的行数据绑定
表克隆:以前学过,但没用。昨天使用了一把,还是经验太少的缘故啊:
newTable=proTypeTable.clone();在新表中将复制另外一个表的架构和约束
DataRow[]不能作为数据源,必须要放到表中或其它类型的数组。