I having a problem maintaining a list of strings. The list is instantiated in OnInit and set as the data source for a GridView. (The basic idea is that the user enters something in the text box, and it appears in the GridView, as many times as they want.)
It works just fine for the first entry, whatever the user enters shows up in the GridView, pretty as can be. However, on following entries, any previously entered values disappear – OnInit is executed again, the List<string> is re-instantiated, and the previous values are over-written. I tried moving the OnInit logic into OnPreInit but just got a Null Reference Exception on the list.
Here’s a contrived example of what I’m trying to do:
I have a TextBox, a Button and a Gridview:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Add"
onclick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="true"></asp:GridView>
In the code behind:
protected override void OnInit(EventArgs e)
{
List<string> gvValues = new List<string>();
GridView1.DataSource = gvValues;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
gvValues.Add(TextBox1.Text);
GridView1.DataBind();
}
I’ve created objects in OnInit in the past, and haven’t had a problem with their state persisting. Obviously I’m missing something here. Someone please point out the flaw in my logic and suggest a method for achieving this functionality.
The below code is tested an it works.