Accesing server control from withing app_code class
Posted
by
OverSeven
on Stack Overflow
See other posts from Stack Overflow
or by OverSeven
Published on 2010-12-26T22:48:06Z
Indexed on
2010/12/26
22:53 UTC
Read the original article
Hit count: 185
My question is about how to acces a server control (listbox) that is located in default.aspx. I wish to acces this control in Functions.cs (this class is located in the App_Code folder).
My page structures: - 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 acces to this control: (this code is located in Functions.cs in App_Code). This is basicly showing some items in the listbox that are located in the 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 acces 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 funcion ListItems in the Default.aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
Functions.ListItems();
}
Regards.
© Stack Overflow or respective owner