我在ASP.net上很新,我试图验证我的SQL DB的一些输出。
我想测试我的数据库中的“img”是否设置为somthing,如果,我不想输出它。
<asp:SqlDataSource ID="selectFromNews" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:DatabaseConnectionString1.ProviderName %>"
SelectCommand="SELECT * FROM [news] ORDER BY [time] DESC">
</asp:SqlDataSource>
<asp:Repeater ID="newsRepeater" runat="server" DataSourceID="selectFromNews" onitemcommand="newsRepeater_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<div class="newsBox">
<h1><%# Eval("title") %></h1>
/* Test if "img" is set to somthing, and output it here, if not, do somthing else */
<p><%# Eval("text") %></p>
</div>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
我在想从后面的代码中获取数据,然后测试并将输出发送回Literal,但是不知道我将如何从那里访问中继器数据?
答案 0 :(得分:3)
首先在Repeater中添加图像控件
<asp:Image ID="ImageID" runat="server" ImageUrl='<%# Eval("img")%>' Visible="false" />
然后在转发器的ItemDataBound事件中将此图像控件作为
protected void YourRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
Image ImageID= e.Item.FindControl("ImageID") as Image;
// now play with your ImageID control..
}
}
答案 1 :(得分:0)
不幸的是,在转发器中使用<% If ... Else ... End %>
块是不可用的(相信我,我已经多次想要它们了。)
最简单的方法是调用代码隐藏函数。例如......
protected string MyFunction(RepeaterItem row)
{
// return based on row.DataItem value
return (row.DataItem.ImgExists ? "Image" : "No Image");
}
然后在标记中,您只需传递Container
对象...
<%#MyFunction(Container)%>
编辑 ...虽然对于更复杂的视觉变化,我会推荐Tim和Usman(以及Nikhil)提供的ItemDataBound
解决方案
答案 2 :(得分:0)
您应该使用转发器的ItemDataBound
事件:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem ri = e.Item;
DataRowView dr = (DataRowView)ri.DataItem;
Panel Panel1 = (Panel)ri.FindControl("Panel1");
// do your evaluation here according the values in the DataRowView
// use ri.FindControl("ID") to find controls in the Itemtemplate
}
ASPX:
<ItemTemplate>
<asp:Panel id="Panel1" runat="server" class="newsBox">
<h1><%# Eval("title") %></h1>
add controls here with runat=server, then you can find them from codebehind
<p><%# Eval("text") %></p>
</asp:Panel>
</ItemTemplate>