ASP.NET, VB: how to access controls inside a FormView from the code behind?

Sara picture Sara · Dec 18, 2010 · Viewed 25.7k times · Source

I have a checkbox and a panel inside of a FormView control, and I need to access them from the code behind in order to use the checkbox to determine whether or not the panel is visible. This is the code that I originally used, but since I put the controls inside of the FormView, it no longer works.

Protected Sub checkGenEd_CheckedChanged(ByVal sender As Object, _
                                         ByVal e As System.EventArgs)
    If checkGenEd.Checked = True Then
        panelOutcome.Visible = True
    Else
        panelOutcome.Visible = False
    End If
End Sub 

I've started to figure this out based on other questions I looked up on here, but all of them were in C# instead of VB, so this is as far as I got:

Protected Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
    If FormView1.CurrentMode = FormViewMode.Edit Then

    End If
End Sub

So yeah I'm not sure exactly how to finish it. I'm sorry, this might be pretty basic, but I'm new at this and any help would be appreciated!

EDIT: here's my code now:

Protected Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
    If FormView1.CurrentMode = FormViewMode.Edit Then

        CheckBox checkGenEd = formview1.FindControl("checkGenEd");
        Panel panelOutcome = formview1.FindControl("panelOutcome");

    End If
End Sub

It's also saying that checkGenEd and panelOutcome are not declared.

EDIT: I changed my code to this but it still doesn't work:

Protected Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
    If FormView1.CurrentMode = FormViewMode.Edit Then

        Dim checkGenEd As CheckBox = FormView1.FindControl("checkGenEd")
        Dim panelOutcome As Panel = FormView1.FindControl("panelOutcome")

        If checkGenEd.Checked = True Then
            panelOutcome.Visible = True
        Else
            panelOutcome.Visible = False
        End If

    End If
End Sub

There aren't any errors anymore, but nothing happens when I click the checkbox. I think there needs to be some kind of event to trigger it but I don't know how you can put an event handler inside of an event handler.

Answer

Brian Mains picture Brian Mains · Dec 18, 2010

With FormView, you have to use find control, as in:

CheckBox checkGenEd = (CheckBox)formview1.FindControl("checkGenEd");
Panel panelOutcome = (Panel)formview1.FindControl("panelOutcome");

You cannot reference a control directly by ID.

HTH.