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 to 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.