I have 2 pages , one to add data to database , and the other to edit it, so in the add I have a CheckBoxList , I added them as follow in the database
URLS : 1,2,3,4,5
and the numbers are the values “keys” from the checkbox
I used this code
String values = "";
foreach (ListItem i in CheckBoxList1.Items)
{
if (CheckBoxList1.Items.Count == 1)
values += i.Value;
else
if (i.Selected)
{
values += i.Value + ",";
}
}
and then I added the values to the database , and it worked perfect ,
now my problem is in the edit page ,as first I want to show the checked boxes from the database , I used this but its not working
in the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
... connection to the database .. etc
try
{
con.Open();
rd = cmd.ExecuteReader();
if (rd.Read())
{
String values = rd["urls"].ToString();//workes perfect
string[] arr = values.Split(',');//works perfect
int x = CheckBoxList1.Items.Count;//this will get me a zero
foreach (ListItem item in CheckBoxList1.Items)// doesnt enter here
{
foreach (string s in arr)
{
if (item.Text == s)
{
item.Selected = true;
}
}
}
.... //exceptions handling
my code for the aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="urls_ds"
DataTextField="name" DataValueField="id">
</asp:CheckBoxList>
<asp:SqlDataSource ID="urls_ds" runat="server"
ConnectionString="<%$ ConnectionStrings:testing_cs %>"
SelectCommand="SELECT * FROM [tbl_urls]"></asp:SqlDataSource>
I am getting the checkboxlist from the database using SqlDataSource , and in the page I can see them put as I print the count of the items its zero
where could be the problem ??
Thanks
Edit : This post describes your problem exactly http://forums.asp.net/t/1488957.aspx/1, and offers two solutions
Here is what I see
This means you are on a NEW copy of the page, so CheckBoxList1 is empty until you load it with data. which I bet happens further down in your code. Just make sure you load it before you use it.
Edit : When using a SqlDataSource to populate controls, you must remember that controls referencing it bind AFTER Page_Load execution. The link above gives two work around methods (either manually calling Control.DataBind or handling the Control.Databound event).