FindControl problem

  • Thread starter Thread starter dodgeyb
  • Start date Start date
D

dodgeyb

I'm trying to check my html checkbox from a postback. This works fine:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim chk As HtmlInputCheckBox
chk = CType(FindControl("chk101228"), HtmlInputCheckBox)
chk.Checked = False
End Sub

However, if I generate the htmlcheckbox on page load event and write
it out to a literal control, the above procedure fails - control
cannot be found.

Protected Sub Form1_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Form1.Load
Me.literal1.Text = "<input runat='server' type='checkbox'
name='chk101228' id='chk101228' checked='checked' />"

End Sub

Why is this ?
Cheers
Chris
 
You aren't creating the checkbox correctly. Simply writing the code for a
checkbox and assigning it to the text of a literal control doesn't create
the object in memory.

You'd need to do this:

dim chk As New System.Web.Ui.Webcontrols.Checkbox()
chk.ID = "chkSomething"

-Scott
 
dodgeyb said:
I'm trying to check my html checkbox from a postback. This works fine:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim chk As HtmlInputCheckBox
chk = CType(FindControl("chk101228"), HtmlInputCheckBox)
chk.Checked = False
End Sub

However, if I generate the htmlcheckbox on page load event and write
it out to a literal control, the above procedure fails - control
cannot be found.

Protected Sub Form1_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Form1.Load
Me.literal1.Text = "<input runat='server' type='checkbox'
name='chk101228' id='chk101228' checked='checked' />"

End Sub

Why is this ?
Cheers
Chris

A literal control containing a checkbox tag with runat="server" will not
work like a checkbox server control.
It will appear in the page as a checkbox, but it will have none of the
server side functionality, such as the possibility to find the control with
FindControl.

Instead of:
Me.literal1.Text = "<input runat='server' type='checkbox' name='chk101228'
id='chk101228' checked='checked' />"

Use a placeholder instead of a literal control, and something like:
Dim cb As New Checkbox()
cb.Id=chk101228
cb.Checked=true
Me.placeholder1.AddControl(cb)
 
Back
Top