Srange Object error

G

Guest

Hi tere, I have a seperate class called Author:

using System;

namespace DocumentControl
{
/// <summary>
/// Summary description for Author.
/// </summary>
public class Author
{
private string strReport = "";
private string strIssue = "";
private string strAuthors = "";

public Author(string strReport, string strIssue, string strAuthors)
{
this.strReport = strReport;
this.strIssue = strIssue;
this.strAuthors = strAuthors;
}

public string StrReports
{
set
{
strReport = value;
}
get
{
return strReport;
}
}

public string StrIssue
{
set
{
strIssue = value;
}
get
{
return strIssue;
}
}

public string StrAuthor
{
set
{
strAuthors = value;
}
get
{
return strAuthors;
}
}


}
}

I declare the object in the parent class:

private Author objAuthor = null;

I create the object on a Button Event whcih works fine and the values are in
the object.

private void AddAuthor(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
objAuthor = new Author(e.Item.Cells[2].Text, e.Item.Cells[6].Text,
e.Item.Cells[12].Text);
}

Now I try to access the object from a different Button Click event:

private void ButtonAddAuthor_Click(object sender, System.EventArgs e)
{
TextBox3.Text = objAuthor.StrReports;
TextBox4.Text = objAuthor.StrIssue;
TextBox5.Text = objAuthor.StrAuthor;
}

But I get the error: Object reference not set to an instance of an object

Why can't I access the objects content? What is wrong? Thanks a lot for any
feedback

Chris
 
D

Dmytro Lapshyn [MVP]

Hi Chris,

The Web page class is not retained between subsequent HTTP requests. When
you first click the button and thus make a postback to the server, your
code-behind class is instantiated, an instance of the Author class gets
initialized in the event handler, but as long as this request is processed,
the whole instance of the code-behind class is recycled.

When you click the other button, a completely new instance of the
code-behind class is created, in which objAuthor is initialized to the null
reference, thus giving you the error.

If you need to retain an instance of a class between requests, you can store
it in the Session object (will work on per-used basis), in the Application
object, or in the Cache. Each scenario has its advantages and drawbacks, I
think you should refer to ASP .NET MSDN docs for more details.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top