I have DataTable which feeds a dropdown list. The values of this dropdown persist when I click on the button whereas the datatable which feeds the list is null at next page reload. I need that this dataTable to also persist like its associated control so isn’t there anything that asp.net has in its tricks bag to behave like for controls but for private members instead ?
public partial class _Default : System.Web.UI.Page
{
private DataTable m_DataTable = new DataTable();
private void f(String x, String y){
// some function of x,y
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
m_DataTable.Columns.Add("Title");
m_DataTable.Columns.Add("x");
m_DataTable.Columns.Add("y");
m_DataTable.Rows.Add("place1", "1", "2");
m_DataTable.Rows.Add("place2", "3", "4");
int nTotalRecords = m_DataTable.Rows.Count;
for (int i = 0; i < nTotalRecords; i++)
{
DropDownList1.Items.Add(m_DataTable.Rows[i]["Title"].ToString());
}
DataRow[] dataRowArray = m_DataTable.Select("[Title]='place1'");
String x = dataRowArray[0]["x"].ToString();
String y = dataRowArray[0]["y"].ToString();
f(x, y);
}
}
protected void ButtonGo_Click(object sender, EventArgs e)
{
// this code will crash because m_DataTable is emptied when page reloads
DataRow[] dataRowArray = m_DataTable.Select("[Title]='place2'");
String x = dataRowArray[0]["x"].ToString();
String y = dataRowArray[0]["y"].ToString();
f(x, y);
}
}
Update: I heard that asp.net paradigm was to be as close as possible as desktop. Why does it create a new instance for the page instead of keeping it ? Why does it keep the same state for controls and not for private members that is incoherent isn’t it?
You can put it in view state:
and retrieve it after postback:
The drawback is of course that the serialised data is sent to the client and back again, which increases the weight of the postback.
Another alternative is to store it in the user session:
and retrieve it after postback:
The drawback of that is of course that you increase the memory load on the server.
Consider the drawbacks of each method, and weight that against how much it costs to get the data again. Sometimes time is the cheapest resource.