开发者

Panel with in Listview gives me an error(Object reference not set to an instance of an object.)

I have a panel in Itewmtemplate of list view it's only supposed to show when user is logged in, by default the visibility = false. Help is appreciated.

here is my c# code:

    Panel pnlOptions = (Panel)ListView1.FindControl("pnlOptions");
    pnlOptions.Visible = true;

Aspx Code:

<asp:Panel ID="pnlOptions" runat="server" Visible="false">
    <ul>
        <ul>
        <li style="float: left">Option 1:</li>
        <li style="float: left">dropdown here</li>
        </ul>
    <li style="float: left">Option 1:</li>
    <li style="float:开发者_运维百科 left">dropdwon here</li>
    </ul>

    </asp:Panel>


You're getting the error because the FindControl call is either:

  1. Failing - If the item is not found as a child of the control, FindControl returns null.

  2. Finding the "wrong" object, and the cast to (Panel) is failing.

I'd recommend rewriting the code as:

Control control = ListView1.FindControl("pnlOptions");
Panel pnlOptions = control as Panel;
pnlOptions.Visible = true;

You can then set breakpoints, and figure out which of the lines is failing on you.


My problem was I was trying to acces it wrongly through a function I created when I was supposed to use the Item_Created Event here is the final working code:

protected void ListView1_ItemCreated(object sender, ListViewItemEventArgs e)
{
    Control control = e.Item.FindControl("pnlOptions");
    Panel pnlOptions = control as Panel;
    pnlOptions.Visible = true;
}

Thanks Reed.


This should work also:

 foreach (var item in ListView1.Items)
  {
    Panel pnlOptions = (Panel)item.FindControl("pnlOptions");
    pnlOptions.Visible = true;
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜