views:

138

answers:

3

In my simple starter asp page I create a DataTable and populate it with two rows. The web site allows users to add new rows. My problem is the DataTable doesn't save the information. I've stepped through the code and the row gets added but the next time a row is added it's not there, only the original two and the newest one to get entered.

I have gotten around this, in an inelegant way, but am really curious why the new rows are being saved.

My code:

    protected void Page_Load(object sender, EventArgs e)
    {
        _Default.NameList = new DataTable();
        DataColumn col = new DataColumn("FirstName", typeof(string));
        _Default.NameList.Columns.Add(col);
        col = new DataColumn("LastName", typeof(string));
        _Default.NameList.Columns.Add(col);
        DataRow row = _Default.NameList.NewRow();
        row["FirstName"] = "Jane";
        row["LastName"] = "Smith";
        _Default.NameList.Rows.Add(row);
        row = _Default.NameList.NewRow();
        row["FirstName"] = "John";
        row["LastName"] = "Doe";
        _Default.NameList.Rows.Add(row);
    }

    protected void AddButton_Click(object sender, EventArgs e)
    {
        DataRow row = _Default.NameList.NewRow();
        row["FirstName"] = this.TextBox1.Text;
        row["LastName"] = this.TextBox2.Text;
        _Default.NameList.Rows.Add(row);
        _Default.NameList.AcceptChanges(); // I've tried with and without this.
    }

I've tried saving them to GridView control but that seems like quite a bit of work. I'm new to ASP.Net but have done windows programming in C# for the last two years.

+1  A: 

You're creating a new DataTable object each time the page loads.

You need to persist the DataTable object to session state or a static variable, or save the data to a database.

SLaks
A: 

Remember that handling events like your button click requires a full postback. You don't run just the click code, you run your entire page lifecycle on a new instance of your page class. The new instance of your page class means a new instance of the datatable as well.

Joel Coehoorn
A: 

The issue here is that your DataTable is being created every time your page loads and it goes out of scope when your page has finished loading and been displayed to the user. To get your desired effect, you will need to store the DataTable in either Session, ViewState, cache, use a control like GridView that will automatically store the underlying data in its state, or something else.

Since you're new to ASP.NET, check out your options for state management.

wsanville