I have a CheckBoxList, whose items are dynamically updated. In the case where all the items are removed from the list, the whole list is disappearing entirely, including the CSS tied to it, which messes up my layout. I don't even see any trace of it in the web developer console. I still want the list to stick around regardless of whether it's empty.
How can I keep the CheckBoxList around, even when it has no items?
Well, if you set a control visible = false, then of course it is never rendered nor sent to the client side.
However, for say a GridView, then you can set ShowHeaderWhenEmpty="true", and it will show the header, even if no data is returned.
Same goes for the CheckBoxList. You can set RenderWhenDataEmpty="True", and it will render to the client side.
Say this markup:
<style>
.chkboxes input {margin-right:10px;
width:20px;
height:20px;
cursor:pointer;
display:inline;
}
.chkboxes label {margin-right:20px;
white-space:nowrap;
font-size:18px;
}
.chkboxes span {display:inline;white-space:nowrap}
</style>
<h3>Select Hotels</h3>
<asp:CheckBoxList ID="ckHotels" runat="server"
RenderWhenDataEmpty="True"
RepeatLayout="Flow"
DataValueField="ID"
DataTextField="HotelName"
RepeatDirection="Vertical"
CssClass="chkboxes"
>
</asp:CheckBoxList>
Note that if you use RenderWhenDataEmpty="True", then your have to use RepeatLayout="Flow", as table layout not supported for the render when empty = true.
So, code behind might be this:
Sub LoadCheckbox()
Dim strSQL As String =
"SELECT ID, HotelName FROM tblHotelsA WHERE ID = 0
ORDER BY HotelName"
ckHotels.DataSource = MyRst(strSQL)
ckHotels.DataBind()
End Sub
For above, of course no rows will be retunred, but a "span" is sent to the client side.
With this code:
Sub LoadCheckbox()
Dim strSQL As String =
"SELECT ID, HotelName FROM tblHotelsA
ORDER BY HotelName"
ckHotels.DataSource = MyRst(strSQL)
ckHotels.DataBind()
End Sub
Then I have this result: