使用FindControl“未设置对象引用”

时间:2014-06-25 19:41:14

标签: asp.net vb.net nullreferenceexception

我试图遍历我的aspx页面上的下拉控件这里是我的代码:

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

我得到一个"对象引用没有设置为对象的实例"

这是我的aspx页面(我正在搜索其他答案,其中讨论了我尝试过的控件层次结构 - 但失败了)

<%@ 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>

1 个答案:

答案 0 :(得分:1)

您收到Object reference not set to an instance of an object因为 dropDown NULLNOTHING。在处理对象时,最好检查NULL或NOTHING。

当我需要查找控件时,我总是将它们放在DIV runat="server"属性中,这样我就知道它们的确切位置。

以下单向让它发挥作用:

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

顺便说一句,由于您的每个DropDownLists都有runat = "server",因此您应该能够直接向其添加,而无需通过执行以下操作来“找到它”:

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