In the below code I am getting a Null Reference Exception error while using "Names.Add(string)" method. But when I use a static class or a static object of the NamedDB class it works fine. Can any one explain how object instances work in ASP.Net web applications ? Why am I getting errors in nonstatic objects while static objects are working fine ?
public partial class _Default : System.Web.UI.Page
{
NameDB Names; //Creating Object
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Names = new NameDB();//Instantiation
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Names.Add("dss");//Object Reference is null
GridView1.DataSource = Names.GetName();
GridView1.DataBind();
}
}
//NamedDB class
public class NameDB
{
List<string> Names=new List<string>();
public void Add(string item)
{
Names.Add(item);
}
public string Remove(string item)
{
Names.Remove(item);
return item;
}
public List<string> GetName()
{
return Names;
}
}
You do not have instances of global object which are instantiated before post back. Instantiate the object again in
Button1_ClickNow You would be expecting the collection to hold data between post back but you wont get it until you store it some where like
database,files,session,viewstateorcachefor data. Session and ViewState are not meant for storing that type of data though.