Reputation: 283
I have a div in an aspx page which is set to runat server.
<div class="article-container" runat="server" id="divArticleContainer"></div>
Now this div is going to have a user control added to it through a static method:
public static void LoadCurrentArticle(int index)
{
divArticleContainer.Controls.Clear();
Page pg = new Page();
string path = @"/Frontend/Controls/Article/ArticleItem.ascx";
ArticleItem control = (ArticleItem)pg.LoadControl(path);
control.Functionality.article = Functionality.articles.ElementAt(index);
divArticleContainer.Controls.Add(control);
}
Basically to give you a brief overview my program is loading a list of news articles. On a touch gesture (swipe left or right) an ajax call to a web method GetNext() and GetPrevious() will move either to the next item or previous item in the list.
[WebMethod]
public static void GetNext(int index)
{
int idx = index;
idx++;
if (idx < Functionality.articles.Count())
{
LoadCurrentArticle(idx);
Functionality.index = idx;
}
else
{
idx = 0;
LoadCurrentArticle(idx);
Functionality.index = idx;
}
}
[WebMethod]
public static void GetPrevious(int index)
{
int idx = index;
idx--;
if (idx >= 0)
{
LoadCurrentArticle(idx);
Functionality.index = idx;
}
else
{
idx = Functionality.articles.Count() - 1;
LoadCurrentArticle(idx);
Functionality.index = idx;
}
}
My MAIN problem is the fact that the 'divArticleWrapper' is returning a null reference exception. Is there a work around to this problem?
Upvotes: 2
Views: 1284
Reputation: 176896
In Static method you cannot access the page controls divArticleWrapper
...
you cant access nonstatic controls from a static method.
static methods can access static variables only..
EDIT
Static methods cannot access instance state (such as a non-static control). Either remove static from the method declaration, or pass a reference to the control as argument to the method:
private static void YourStaticMethod(HtmlControl div)
{
//than do your task
}
...and call it like so:
YourStaticMethod(divArticleWrapper);
Upvotes: 4