Click here to Skip to main content
15,889,412 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello ,
I am using static list of string in my asp.net(C#) Code like
C#
private static List<string> newlist = new List<string>();

Now I have one textbox from which i am taking input string and adding in to list on button click like
C#
protected void Button1_Click(object sender, EventArgs e)
   {
       newlist.Add(TextBox1.Text);
       TextBox1.Text = "";

   }

And on another button click i am showing this list on literal control using foreach loop like this,
C#
protected void Button2_Click(object sender, EventArgs e)
    {
        ltrList.Text = "";
        foreach(var l in newlist)
        {
            ltrList.Text += l.ToString() + "<br/>";
        }
    }


I have host this page on server. When at a time to users access this webform and add items in list giving input from textbox the items show to eachother to both users.
Suppose one user add "Veeshal" and add to list and another user add "Amol" and add to list. And when they click on show, both users will get all items from list "Veeshal" and "Amol".
I think it's because of static. How to solve this problem. I don't want to show the list of items to each other.

What I have tried:

I have tried
protected void Button2_Click(object sender, EventArgs e)
{
ltrList.Text = "";
foreach(var l in newlist)
{
ltrList.Text += l.ToString() + "
";
}
}
Posted
Updated 17-Jul-16 18:51pm

Simple: don't use static.
The problem is that static variables are available to all instances of a class in an application - which for a web site can be (but may not be) a number of user sessions.
Instead, store your list in the Session - in your Page_Load you check if it exists, and retrieve it if it does. If it doesn't, you then create it. Either way, you store it as a class level instance variable, not static.
When you finish adding items to it, you put it back into the Session for next time.
 
Share this answer
 
In addition to above solution,

you shall do this in a simpler way using hidden field

create a hidden field control in aspx
ASP.NET
<asp:HiddenField ID="hdnfldList" runat="server" />

and you shall append the text from textbox to the literal control

C#
protected void Button1_Click(object sender, EventArgs e)
       {
            ltrList.Text += TextBox1.Text + "<br/>";
            TextBox1.Text = "";

       }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900