Shortstuff81000
Shortstuff81000

Reputation: 479

How do I find enabled/disabled controls using a foreach loop in VB.net?

I am creating a simple guessing game. Many of the controls are repetitive, so I'd like to loop through them to databind and search for enabled or disabled controls. When I try to run the page after coding either foreach method in my code, I get an "object reference not set to an instance of an object" error.

How would I fix this without creating a new instance of my control? I've tried that already; it doesn't overwrite the existing control on my aspx page. Obviously it is creating new ones somewhere, but I'm not sure where; I don't see well. When I work on the computer I do it at 350% - 400% magnification.

Here is a sample of my aspx page:

<div class="Character">
    <img src="Images/1.png" style="width: 100%;" /><br />
    <asp:DropDownList ID="DDL1" runat="server" CssClass="BigText"></asp:DropDownList><br />
    <asp:Button ID="BTN_SubmitGuess1" runat="server" CssClass="BigText Button2" Text="Submit Guess" />
</div>

Here is a sample of my codebehind. I have written my code for both databinding and finding enabled or disabled controls in it:

Dim arr() As String = {"One", "Two", "Three", "Four", "Five"}
Dim ddlControls() As DropDownList = {DDL1, DDL2, DDL3, DDL4, DDL5} 

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        'What I have now
        DDL1.DataSource = arr
        DDL1.DataBind()
        ...
    'What I'd like to have
    For Each ddl As DropDownList In ddlControls
        ddl.DataSource = arr
        ddl.DataBind()
    End If

    Dim remaining As Integer

    For Each ddl As DropDownList In ddlControls
        If ddl.Enabled = True Then
            remaining += 1
        End If
    Next

    LBL_Remaining.Text = CStr(remaining)
End Sub

Upvotes: 1

Views: 149

Answers (1)

Muhammad
Muhammad

Reputation: 1360

You have to set the values of your ddlControls array while the page is loading once the DropDownList controls are already created :

Dim arr() As String = {"One", "Two", "Three", "Four", "Five"}
Dim ddlControls() As DropDownList

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        ddlControls = {DDL1, DDL2, DDL3, DDL4, DDL5} ' <<======= HERE
        DDL1.DataSource = arr
        DDL1.DataBind()
        For Each ddl As DropDownList In ddlControls
            ddl.DataSource = arr
            ddl.DataBind()
        Next
End If

    Dim remaining As Integer

    For Each ddl As DropDownList In ddlControls
        If ddl.Enabled = True Then
            remaining += 1
        End If
    Next

    Me.Title = CStr(remaining)
End Sub

Upvotes: 1

Related Questions