Read values from dynamically added checkbox

markie13

Newcomer
Joined
Dec 31, 2003
Messages
3
Location
Dallas, TX
I am having a heck of a time reading the value of a dynamically generated checkbox. Here's the code
Code:
        For Each dr In ds.Tables(0).Rows
            tr = New TableRow
            'cell #1
            tc = New TableCell
            With tc
                .Text = dr(1)
                .BackColor = White
            End With
            tr.Cells.Add(tc)
            'cell #2
            tc = New TableCell
            ckbx = New CheckBox
            With ckbx
                .ID = dr(0)
                .Font.Size = FontUnit.XXSmall
                .Font.Name = "verdana"
                .Checked = isProcessChecked(dr(0))
                .Visible = True
                AddHandler .CheckedChanged, AddressOf btnSave_Click
            End With
            With tc
                .ID = "phred"
                .BackColor = White
                .Controls.Clear()
                .Controls.Add(ckbx)
            End With
            tr.Cells.Add(tc)
            tbl.Rows.Add(tr)
        Next
And, the event that is supposed to read the checkbox:

Code:
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim check As CheckBox = CType(tbl.FindControl("phred5"), CheckBox)
        lbl.Text = check.Checked 
    End Sub
When I do this, I get a error that says 'Object reference not set to an instance of an object.' I'm pretty sure this means it can't find my control labeled 'phred5.' This, I understand. What I don't understand is why. I know the checkbox is there - I can click on it - but when I hit submit and go to this event handler, it's like it disappears, even though I have added it.

Any help would be appreciated

mark
 
Look at the order in which the page executes. Your controls need to be created first, then it checks Postback data against your controls. Then it raises the Postback event. So, after you postback, you need to create your controls again, then you can retrieve the values from the Postback.
 
Back
Top