Sharing an object between methods in same class (with postback)
I have a user control with a number of methods. I also have a dataset object that I'm filling in one method, but I also need to access that same dataset (and the data in it) in another.
I am filling the dataset from some xml that I get from a webservice when someone clicks on a button. The data from the dataset is then bound to a listbox control. When someone selects an item in the list control (I have autopostback set to true on it) it then fires off another method and it's this method where I need to access the data in the dataset, but when I check the immediate window it's telling me that the dataset is set to null.
Where am I going wrong?
Edited t开发者_如何学Goo add psuedocode
//Dataset
DataSet dsAddress;
protected void Page_Load(object sender, EventArgs e)
{
// Nothing happens to DataSet here
}
protected void btnPostCode_Click(object sender, EventArgs e)
{
try
{
// Dataset has data added here
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
}
if (!DataHelper.DataSourceIsEmpty(dsAddress))
{
//Dataset bound to listbox here
}
}
protected void lstAddressDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
// Need to access dataset here
}
If the data is the same across all users of the system (irrespective of session), make the dataset static or store in the Application object.
Otherwise, if it is per-session, store in the Session object but do not forget to clean up after it is not needed any longer.
In my opinion, it is unwise to store it in the viewstate as that will create much additional traffic, and will slow down the system with serialization and deserialization.
you can use session variables , you can store your dataset in a session variable and access the data util session expired
You will have to save your dataset in the viewstate or as a session variable.
Take a look @
http://msdn.microsoft.com/en-us/library/ms972976.aspx
http://msdn.microsoft.com/en-us/library/ms227551(VS.80).aspx
http://codeforeternity.com/blogs/technology/archive/2007/12/19/handling-asp-net-session-variables-efficiently.aspx
When are you populating the dataset? Can't you just populate it again? It should be populated in Init for user controls, providing that it doesn't require any postback information in order to retrieve the data.
精彩评论