My question is about accessing a server control (listbox) that is located in default.aspx.
I wish to access this control in Functions.cs (this class is located in the App_Code folder).
My page structure is:
- 1 masterpage with 1 content holder
- Default.aspx (all the controls are within the content place holder)
- Functions.cs (located in App_Code)
Now when I try to fill up the listbox elements I get the error "object reference not set to an instance of an object."
What I have tried to gain access to this control: (this code is located in Functions.cs in App_Code). This is basically showing some items in the listbox that are located in an xml file
private static string file = HttpContext.Current.Server.MapPath("~/App_Data/Questions.xml");
public static void ListItems()
{
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(file);
XPathNavigator nav = XMLDoc.CreateNavigator();
XPathExpression expr;
expr = nav.Compile("/root/file/naam");
XPathNodeIterator iterator = nav.Select(expr);
//ATTEMPT to get access to ServerControl(listbox)
Page page = (Page)HttpContext.Current.Handler;
ListBox test = (ListBox)page.FindControl("lbTest"); //control is called lbTest in Default.aspx
test.Items.Clear();
while (iterator.MoveNext())
{
test.Items.Add(iterator.Current.Value);
}
}
Code from the default.apx file
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterFile.master" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="default" Debug="true" %>
<%@ MasterType TypeName="Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" Runat="Server" >
<asp:MultiView ID="mvTest" runat="server" >
<asp:View ID="vCollection" runat="server">
<asp:ListBox ID="lbTest" runat="server" CssClass="listbox" ></asp:ListBox>
</asp:View>
</asp:MultiView>
</asp:Content>
The masterfile itself just has 1 placeholder.
Then I call upon the function ListItems in the Default.aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
Functions.ListItems();
}