Marius Vasile

Marius Vasile

  • 586
  • 1.8k
  • 136.8k

Adding data to List double the displayed data

Oct 31 2023 8:22 PM

I am adding data to a List, save it as a Session and then use it. What I don't want to is to have duplicatres in the list. This is what I use

public List<string> values = new List<string>();
protected void Page_Load(Object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        if (Session["MyList"] == null)
        {
            Session["MyList"] = new List<string>();
        }
    }
}

protected void btnAddClick(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txtActivitate.Text))
    {
        var text = txtActivitate.Text.ToString();
        values = Session["MyList"] as List<string>; // Retrieve the list from the session
        lock(values)
        {
            if (!values.Contains(text))
            {
                values.Add(text);
                Session["MyList"] = values;

                foreach (string value in values)
                {
                    Message.Text += value + "<br />";
                }

                txtActivitate.Text = string.Empty;
                txtActivitate.Focus();
            }
            else
            {
                txtActivitate.Text = string.Empty;
                txtActivitate.Focus();
            }
        }
    }
}

On first click I got the right value entered. On the second click, I get the first value doubled and new value. On third click I get all the previous values plus the new one. What am I doing wrong, please?


Answers (4)