Friday, June 20, 2008

Binding CheckBoxList with Arraylist -A Problem

Though I can bind the ArrayList as a DataSource for the checkBoxList Control, but it became a problem for me. When I tried to get the selected item
----------------------
CheckBoxList1.Items[i].Checked
---------------------------
It always returns false, no matter you check the checkboxes or not.
So, To get rid of this roadblock I had to use DataTable as the DataSource.

2 comments:

sonesh said...

This seems very very weird to me.
I recently used CheckBoxList in my project, and I used
CheckBoxList1.Items[i].Selected
rather than
CheckBoxList1.Items[i].Checked

So, I went to that piece of code, and saw that CheckBoxList.Items[i] does not even have the property Checked. So I am wondering how your code even compiled. May be we are using different versions of .NET. And I indeed used ArrayList and not DataTable.

Actually, their is a long story behind using this Checkboxlist. Ideally I wanted a dropdownlist with multiple selections just like in the Reporting Services. So, build a custom control, not so easy. I even found some products in the web, however, I had to buy those and one where heavy javascript was used to get the checked Items, so gave up all those and used CheckboxList. Well, Checkboxlist does not have scrolling so if there are many items, the control will look ugly. However, I added scrolling and also an option to select ALL items. Here is the code:

<div style="width:180px; height: 70px; overflow-y:scroll;" class="multiSelectDiv">

<asp:CheckBox ID = "AllChannel" runat = "server" Text = "ALL" AutoPostBack = "True" CssClass="multiSelectChkBox" />

<asp:CheckBoxList ID="channelFilter" runat="server" TabIndex="3" CssClass="multiSelectChkBox" >

</asp:CheckBoxList>

</div>

So the scrolling is on the div, and the autopostback event for checkbox - ALL contains selecting the checkboxlist channelFilter when is checked and vice-versa.

Prabin Shrestha said...

Hey man,I made a mistake in the checkboxlist property.It should be "selected" instead of "checked". You are right. And I also got the root of the problem. I was not following the page Life cycle properly. I was trying to get CheckBoxList1.Items[i].Selected on a Button_clicked event and before this event is called, Page_Load event is called which again binds the checkboxist with DataSource which resets the Properties of checkboxList.