Fverswijver
Fverswijver

Reputation: 465

ViewState null on postback

So I have a listbox on my page and some textfields. Through the textfields I can add an item to my listbox (click the button, it adds it to a private List<string> which is then set as a ViewState and the list is databound again). My listbox is also in an updatepanel which gets triggered on the button's Click event. Problem: My Viewstate remains null on a postback so it gets reset each time.

Some code:

private List<IngredientData> _ingredientsList;

        protected void Page_Load(object sender, EventArgs e)
        {
            // prepare ingredient lists
            _ingredientsList = new List<IngredientData>();

            if (Page.IsPostBack)
            {
                if (ViewState["IngredientsList"] != null)
                {
                    _ingredientsList = (List<IngredientData>) ViewState["IngredientsList"];
                }
            }

            lstIngredients.DataSource = _ingredientsList;
            lstIngredients.DataTextField = "Text";
            lstIngredients.DataValueField = "Name";
            lstIngredients.DataBind();
        }

        protected void btnAddIngredient_Click(object sender, EventArgs e)
        {
            _ingredientsList.Add(new IngredientData { Name = txtIngredientName.Text, Quantity = txtUnitQuantity.Text, Unit = lstUnits.SelectedValue });

            ViewState["IngredienstList"] = _ingredientsList;
            lstIngredients.DataSource = _ingredientsList;
            lstIngredients.DataBind();
        }

Any idea how I can fix this? Am I doing something wrong?

Upvotes: 0

Views: 839

Answers (1)

Town
Town

Reputation: 14906

btnAddIngredient_Click is adding to "IngredienstList" not "IngredientsList" (note the spelling).

You can avoid this kind of typo by using a constant:

private const string IngredientsListViewStateKey = "IngredientsList";

then referring to it like this:

ViewState[IngredientsListViewStateKey] = _ingredientsList;

Upvotes: 3

Related Questions