Friday, March 16, 2012

Object reference not set to an instance of an object.

What I want to do is create all my functions on the functions.cs page and call them when I need them. One of the problems I am having is when I create my function, it's throwing this error:

Object reference not set to an instance of an object.

Here's my code, this is in the functions.cs page:

using System;
using System.Text;

namespace web_isotope.functions
{
public class mainFunctions : System.Web.UI.UserControl
{
public string pageStatus()
{
error-->string strURL = Request.ServerVariables["URL"];
StringBuilder replaceFunc = new StringBuilder(strURL);
strURL = replaceFunc.Replace("/web_isotope/","").ToString();
strURL = replaceFunc.Replace(".aspx","").ToString();
return strURL;

}
}
}

I want to be able to call it from the home.aspx.cs page

Does anyone know why I'm getting this error?
Thanks in advance!You can't request server variables from a .cs file. you might need to use the Request.ServerVariables () function in you .aspx file and then pass that value to the function...

like so:
in your .aspx file

string strURL = Request.ServerVariables["URL"];
mainFunctions objMainFunctions = new mainFunctions();
objMainFunctions.pageStatus(strURL);

and in your .cs

public string pageStatus(p_strURL)
{
StringBuilder replaceFunc = new StringBuilder(p_strURL);
///...
The error is due to the fact that Control doesn't contain a definition of the Request Object. It does, however, define Page (which is the Page that contains the Control) and so you can use Page.Request.ServerVariables["URL"].

I would question why you are inheriting from System.Web.UI.UserControl and how are you instantiating the Control in your code?

0 comments:

Post a Comment