Domanda

I'm building an edit staff member details page. staff members belong to groups that we specify using ListItem within a CheckBoxList (groupsList). Once you select a staff member to edit, a form with all of their details filled out appears, including which groups they currently belong to. I've got this list (this is declared right within the public partial class edit_user: System.Web.UI.Page declaration:

public List<string> groups = new List<string>();

When checking the groups they currently belong to (from a database), I add the group ID (edit: fetched from the database) to the list:

groups.Add(group_id);

Then. when whoever is editing the staff member clicks the 'Save' button, I need to update groups they belong to, which includes deleting a record from the database (hence why I keep track of the groups they belong to on load). I was doing the following:

string group_id;

foreach (ListItem item in groupsList.Items)
{
    g_id = item.Value;
    System.Diagnostics.Debug.WriteLine(g_id);
    if (groups.Contains(g_id))
    {
        System.Diagnostics.Debug.WriteLine("already belongs");
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("doesn't belong");
    }
}

but it was not working, so I wanted to make sure my list had items in it still:

foreach (string i in groups)
{
    System.Diagnostics.Debug.WriteLine(i);
}

and nothing gets printed out. I can not figure out why the list is all of a sudden empty on my OnClick event handler.

È stato utile?

Soluzione

the list is all of a sudden empty on my OnClick event handler.

Event handlers are triggered as the result of a new http request from the browser, and every new http request from the browser means you're working with a new instance of your page class. This commonly confuses people at first: unlike with Windows Forms, your page class form does not remain active in between user events. It is not a living object on the server. Instead, the ASP.Net runtime creates a new instance of your class for each request, and follows the Page Lifecycle with your class to serve exactly one http request from the browser. This page class instance is destroyed as soon as that single request is completed.

You'll also find that this means all of the code for your page class is checked on every request, including events like page_load, page_init, etc.

You need to store this list somewhere that will persist across http requests. The Session is one common option.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top