ASP.NET怎么操作DataTable实例应用(2)


View Code


<asp:Button runat="server" Text="报表2" />
<asp:Repeater runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:HiddenField runat="server" Value='<%# Container.DataItem %>' />
<asp:Repeater runat="server">
<HeaderTemplate>
<table cellspacing="0" cellpadding="5">
<tr>
<td>Name</td>
<td>Quantity</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Name") %></td>
<td><%# Eval("Quantity") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>


首先,我们需要从DataTable,获取名称(Name)唯一的记录存储起来,作为第一个Repeate控件的数据集数据源。

复制代码 代码如下:


View Code


protected void ButtonReport2_Click(object sender, EventArgs e)
{
this.Repeater1.DataSource = Names();
this.Repeater1.DataBind();
}

List<string> Names()
{
List<string> t = new List<string>();
DataTable otable = GetData();
foreach (DataRow dr in otable.Rows)
{
if (!t.Contains(dr["Name"].ToString()))
t.Add(dr["Name"].ToString());
}
return t;
}


我们还要写第二个Repeater控件的数据源:

复制代码 代码如下:


View Code


List<Item> GetDataByName(string name)
{
List<Item> o = new List<Item>();
DataTable otable = GetData();
foreach (DataRow dr in otable.Rows)
{
if (name == dr["Name"].ToString())
{
Item i = new Item(dr["Name"].ToString(), Convert.ToInt32(dr["Quantity"]));
o.Add(i);
}
}
return o;
}


为第二个Repeater控件绑定数据源,在绑写之前,得先找到这个控件,因此,你需要在第一个Repeater控件写OnItemDataBound="Repeater1_ItemDataBound"事件:

复制代码 代码如下:


View Code


protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.Item.FindControl("HiddenField1") != null && e.Item.FindControl("Repeater2") != null)
{
var hiddenField = e.Item.FindControl("HiddenField1") as HiddenField;
var repeater = e.Item.FindControl("Repeater2") as Repeater;
repeater.DataSource = GetDataByName(hiddenField.Value);
repeater.DataBind();
}
}
}

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjdxfy.html