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

标签 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>
<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()

最佳答案

我的猜测是,在 DownloadsRepeater 控件中找不到名为 imagepathlit 的控件,因此 imagepathlit 控件在调用后为 null。

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

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

更新

由于您使用的是中继器,因此子控件的布局略有不同。 Repeater 中的每个 Item 都会有一个 Literal 实例。因此,要获取控件的每个实例,您必须循环遍历 Repeater 中的 Items 并在每个 上调用 FindControl() >项目:

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

关于asp.net - 未将对象引用设置为对象的实例(NullreferenceException 未由用户代码处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2637216/

相关文章:

C 预处理器指令,这是正确的语法吗? #Ifdef foo ||酒吧

c# - 你调用的对象是空的。在 wcf 服务中

c# - 对象引用未设置为对象的实例EDIT

c# - 使用List.Add<t>时出现NullReference异常,想了解一下

jquery - 使用 jquery 隐藏和显示表格行元素

c# - 调整大小和存储图像但锁定以确保它只完成一次

syntax - 我应该使用 Sass 还是 Scss 进行编码?

performance - begin-end block 是否会影响条件语句的性能?

c# - 对 ASP.Net 中 GridView 中的 TextBox 进行 JavaScript 验证

asp.net - DBContext.Entry 的作用是什么?