【问题标题】:Object reference not set to an instance of an object (NullreferenceException was unhandled by user code)对象引用未设置为对象的实例(用户代码未处理 NullreferenceException)
【发布时间】:2011-02-07 21:30:09
【问题描述】:

我怎样才能绕过这个异常?

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

【问题讨论】:

  • 需要更多解释并添加相关代码
  • 你能粘贴转发器的aspx部分吗?确定 imagepathlit 在您要查找的位置不存在。如果您粘贴 aspx,我们可以用适当的方式回答

标签: asp.net syntax nullreferenceexception literals


【解决方案1】:

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

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

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

更新

由于您使用的是中继器,因此子控件的布局会有所不同。对于Repeater 中的每个Item,您将拥有一个Literal 的实例。因此,要获取控件的每个实例,您必须遍历Repeater 中的Items 并在每个Item 上调用FindControl()

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

【讨论】:

  • 文字在.aspx中是这样的;
【解决方案2】:

因为控件在ItemTemplate中,所以不能使用repeater.findcontrol;您必须遍历中继器的项目以查找控件,因为 itemtemplate 是可重复的。所以你必须遍历每一个来寻找控件,如下所示:

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

使用该语法。

【讨论】:

    【解决方案3】:

    假设您发布的代码确实是引发异常的地方,我会说DownloadRepeater 中没有ID 为imagepathlit 的控件。

    检查您的aspx

    【讨论】:

      猜你喜欢
      • 2014-04-19
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 2016-06-05
      • 1970-01-01
      • 2014-07-21
      相关资源
      最近更新 更多