1

I'm trying to loop through my dropdown controls on my aspx page here is the code I have:

Private Sub PopulateDropDowns(ByVal dropDownName As String)

Dim dropDown As DropDownList = CType(Me.FindControl(dropDownName), DropDownList)

dropDown.Items.Add(New ListItem With {.Text = "Somedata", .Value = "123"})

End Sub

I'm getting a "Object reference not set to an instance of an object"

Here is my aspx page (I've search through other answer which talk about the hierarchy of controls which I've tried - but failed)

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="SelectTeam.aspx.vb" Inherits="FCO.SelectTeam" %>

    <asp:DropDownList ID="ddOpenBrd1" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="ddOpenBrd2" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="ddOpenBrd3" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="ddOpenBrd4" runat="server"></asp:DropDownList>

</div>

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Matt D. Webb
  • 3,216
  • 4
  • 29
  • 51

1 Answers1

2

You are getting Object reference not set to an instance of an object because dropDown is NULL or NOTHING. It is always good practice to check for NULL or NOTHING when you are dealing with objects.

When I need to find controls I always put them inside a DIV with runat="server" attribute, this way I know exactly where they are.

The following is one way of getting this to work:

ASPX:

<div id="myControls" runat="server">
    <asp:DropDownList ID="ddOpenBrd1" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="ddOpenBrd2" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="ddOpenBrd3" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="ddOpenBrd4" runat="server"></asp:DropDownList>
</div>

VB.NET Code-Behind:

Private Sub PopulateDropDowns(ByVal dropDownName As String)

    'Notice I am using "myControls" instead of "Me"
    Dim dropDown As DropDownList = CType(myControls.FindControl(dropDownName), DropDownList)

    If dropDown IsNot Nothing Then
        dropDown.Items.Add(New ListItem With {.Text = "Somedata", .Value = "123"})
    End If

End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    PopulateDropDowns("ddOpenBrd1")    
End Sub

BTW, since each of your DropDownLists has runat = "server" then you should be able to add items to it directly, without needing to "find it" by doing something like:

ddOpenBrd1.Items.Add(New ListItem With {.Text = "Somedata", .Value = "123"})
lucidgold
  • 4,432
  • 5
  • 31
  • 51