Asp.net 对象引用未设置为对象的实例(用户代码未处理NullreferenceException)

Asp.net 对象引用未设置为对象的实例(用户代码未处理NullreferenceException),asp.net,syntax,nullreferenceexception,literals,Asp.net,Syntax,Nullreferenceexception,Literals,我怎样才能避开这个例外 Dim imagepathlit As Literal = DownloadsRepeater.FindControl("imagepathlit") imagepathlit.Text = imagepath 这是中继器: <asp:Repeater ID="DownloadsRepeater" runat="server"> <HeaderTemplate> <table width="70%"> <tr&

我怎样才能避开这个例外

Dim imagepathlit As Literal = DownloadsRepeater.FindControl("imagepathlit")
        imagepathlit.Text = imagepath
这是中继器:

<asp:Repeater ID="DownloadsRepeater" runat="server">

<HeaderTemplate>
<table width="70%">
<tr>
<td colspan="3"><h2>Files you can download</h2></td>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td width="5%">
<asp:Literal ID="imagepathlit" runat="server"></asp:Literal></td>
<td width="5%"></td>
<td>&nbsp;</td>
</tr>
</table>
</ItemTemplate>

</asp:Repeater>
c.Open()
        r = x.ExecuteReader
        While r.Read()
            If r("filename") Is DBNull.Value Then
                imagepath = String.Empty
            Else
                imagepath = "<img src=images/" & getimage(r("filename")) & " border=0 align=absmiddle>"
            End If

        End While
        c.Close()
        r.Close()

您可以下载的文件
以下是获取中继器数据的代码:

<asp:Repeater ID="DownloadsRepeater" runat="server">

<HeaderTemplate>
<table width="70%">
<tr>
<td colspan="3"><h2>Files you can download</h2></td>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td width="5%">
<asp:Literal ID="imagepathlit" runat="server"></asp:Literal></td>
<td width="5%"></td>
<td>&nbsp;</td>
</tr>
</table>
</ItemTemplate>

</asp:Repeater>
c.Open()
        r = x.ExecuteReader
        While r.Read()
            If r("filename") Is DBNull.Value Then
                imagepath = String.Empty
            Else
                imagepath = "<img src=images/" & getimage(r("filename")) & " border=0 align=absmiddle>"
            End If

        End While
        c.Close()
        r.Close()
c.Open()
r=x.ExecuteReader
而r.Read()
如果r(“filename”)为DBNull.Value,则
imagepath=String.Empty
其他的
imagepath=“”
如果结束
结束时
c、 关闭()
r、 关闭()

我猜在名为
imagepathlit
下载重复器
控件中找不到控件,因此
imagepathlit
控件在调用后为空

请记住,
Control.FindControl()
根据
ID
而不是控件的名称查找控件。因此,要在集合中找到控件…您必须在应用程序的前面有类似的内容:

Dim imagepathlit As Literal = new Literal()
imagepathlit.ID = "imagepathlit"
更新

因为您使用的是中继器,所以子控件的布局有所不同。对于
中继器中的每个
,您将有一个
文本
的实例。因此,要获取控件的每个实例,必须在
中继器中的
项中循环,并对每个
项调用
FindControl()

For Each item As Item In DownloadsRepeater.Items
    Dim imagepathlit As Literal = item.FindControl("imagepathlit")
Next

假设您发布的代码确实引发了异常,我认为
DownloadRepeater
中没有ID为
imagepathlit
的控件


检查您的
aspx

由于控件位于ItemTemplate内,因此不能使用repeater.findcontrol;由于itemtemplate是可重复的,因此必须循环遍历中继器的项以查找控件。因此,您必须循环遍历每个控件,以查找控件,如下所示:

foreach (var item in repeater.Items)
{
   var control = item.FindControl("ID") as Type;
}

使用该语法。

需要更多解释并添加相关代码。是否粘贴中继器aspx部件?可以肯定的是,imagepathlit在您查找它的地方不存在。如果你粘贴了aspx,我们可以用适当的方式来回答。aspx中的文字如下所示;