C# – Dynamic Table CheckBoxes not having a “Checked” true value


I have been working on a web app using ASP.NET with the code base as C#. I have a dynamic table that resizes based on a return from a SQL query; with a check box added in the third cell of each row. The checkbox is assigned an ID according to an index and the date.

When users hit the submit button, the code is supposed to get a value from each row that is checked. However, when looping through the rows, none of the check boxes ever have a value of true for the Checked property. The ID persists, but the value of the checkbox seems to be lost.

Code for adding the Checkboxes:

cell = new TableCell();  
CheckBox cb = new CheckBox();  
cb.ID = index.ToString() + " " +  lstDate.SelectedItem.Text.ToString();  

if (reader["RestartStatus"].ToString() == "0")  
     cb.Checked = false;  
     cb.Enabled = true;  
     cb.Checked = true;  

The code for getting the checkbox value:

for (int i = 0; i < CompTable.Rows.Count; i++)  
    int t3 = CompTable.Rows[i].Cells[2].Controls.Count;  
    Control temp = null;  
    if (t3 > 0)  
        temp = CompTable.Rows[i].Cells[2].Controls[0];  

    string t2 = i.ToString() + " " + lstDate.SelectedItem.Text.ToString();  
    if ( temp != null && ((CheckBox)temp).ID == i.ToString() + " " +   lstDate.SelectedItem.Text.ToString())  
        //Separated into 2 if statements for debugging purposes  
        //ID is correct, but .Checked is always false (even if all of the   boxes are checked)  
        if (((CheckBox)temp).Checked == true)  

Best Solution

The most likely cause for dynamic controls not having a value is that they were either created after ViewState has been loaded, or read before.

Generally speaking, dynamic controls should be created during the PageInit event, and read during or after the PageLoad event.

Related Question