简体   繁体   中英

ASP.net listview with state

I have a dynamic list in ASP.net front end. User can click a button and add as many entries as it wants.

I'm using ViewState to save this data:

if(ViewState["items"] != null)
{
    ListItems.DataSource = ViewState["items"];
}          
ListItems.DataBind();

And there is a callback as follows:

protected void AddItemClick(object sender, EventArgs e)
{
    List<UserEntry> ue;
    if (ViewState["items"] == null)
    {
        ue = new List<UserEntry>();
    }
    else
    {
        ue = (List<UserEntry>)ViewState["items"];
    }
    ue.Add(new UserEntry());
    ViewState["items"] = ue;
}

It's working fine, the problem is that, every time I add a new item, I loose any data I've entered in the other rows. How can I keep this information?

Edit: I'm calling it from the .aspx page:

<asp:ListView ID="ListItems" class="block" SortExpression="DataType" ItemStyle-Wrap="false"  runat="server">
    <ItemTemplate  >
        <table>
            <tr>
                <asp:TextBox ID="Name" runat="server" class="inline" Text='<%# Eval("text") %>'></asp:TextBox>

            </tr>
        </table>
    </ItemTemplate>
</asp:ListView>

Thanks in advance

Where are you calling this method? Are you calling in the same page? Before you construct the List you might be assigning to ListItems control.

protected void AddItemClick(object sender, EventArgs e)
{
    List<UserEntry> ue;
    if (ViewState["items"] == null)
    {
        ue = new List<UserEntry>();
    }
    else
    {
        ue = (List<UserEntry>)ViewState["items"];
    }
    ue.Add(new UserEntry());
    ViewState["items"] = ue;
    ListItems.DataSource = ue;
    ListItems.DataBind();
}

In this line, you can assign the collection to List and bind while adding in the ViewState.

There could be several points to check:

  1. If you are assigning the values to ViewState on Page_Load then you might not be checking if it is a postback or not to overcome it you could just simply do the values assignment part to ListItems in an if condition: if(!Page.IsPostback){/* do stuff */ }
  2. You might want to bind the ListItems each time you modify your list
  3. You Could simply tweak with your code to see where the issue is nobody can help you investigate your code better than you!
  4. Or finally, you may want to skip the ViewState at all, what you can do is:

     protected void AddItemClick(object sender, EventArgs e) { List<UserEntry> ue = (List<UserEntry>)ListItems.DataSource; if(ue == null) { ue = new List<UserEntry>(); } ue.Add(new UserEntry()); ListItems.DataSource = ue; ListItems.DataBind(); } // Just an idea though 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM