How to hide an item in datalist

大憨熊 提交于 2019-12-11 04:01:22

问题


I want to hide an item in datalist according to some condition suing ItemBound, how ?


回答1:


Wrap a PlaceHolder control around the entire content of the ItemTemplate.

Then in your ItemDataBound event, you could do something like:

Protected Sub myDataList_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.DataListItemEventArgs) Handles myDataList.ItemDataBound
    If Not Value = Value2 Then
       Ctype(e.Item.FindControl("myPlaceHolder"), PlaceHolder).Visible = False
    End If
End Sub

A better approach (however I've not had chance to test it), would be to hide the whole item using e.Item.Visible. This way no HTML table elements would be rendered for the item. It would also mean no PlaceHolder would have to be added.

Protected Sub myDataList_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.DataListItemEventArgs) Handles myDataList.ItemDataBound
    If Not Value = Value2 Then
       e.Item.Visible = False
    End If
End Sub

Alternatively, if the values you are checking are from a database source, you could filter the items out before binding:

WHERE Value=@Value2



回答2:


A simple solution could be to set the visibility of your Item container by evaluating your desired condition in your ItemTemplate:

<ItemTemplate>
    <div id="itemdiv" visible='<%# (Convert.ToInt32(Eval("YourValue")) == 5) %>' runat="server">
        <%# Eval("SomeOtherValue") %>
    </div>
</ItemTemplate>

My example uses a constant but you could use any variable in scope.

Pitfall!

DataList will insist to create empty rows for hidden items, so you may have to use ListView instead to fully control creating your filtered itemlist.


Update

Using a ListView instead will only create rows for visible items:

<ItemTemplate>
    <tr id="itemdiv" visible='<%# (Convert.ToInt32(Eval("YourValue")) == 5) %>' runat="server">
        <td><%# Eval("SomeOtherValue") %></td>
    </tr>
</ItemTemplate>
<LayoutTemplate>
    <table border="1">
        <tr runat="server" id="itemPlaceholder" />
    </table>
</LayoutTemplate>


来源:https://stackoverflow.com/questions/9394887/how-to-hide-an-item-in-datalist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!