Search code examples
c#asp.netclass-designcode-behindaccess-modifiers

Declaring a global variable in ASP.NET codebehind


I want to declare a Dictionary<string, object> variable but don't know where/how to. The values in the dictionary will be objects from the Page (ListBoxes, DropDownLists, etc) so I can't exactly create a helper class somewhere else. Is there any way I can make this variable accessible from each method in the codebehind?


Solution

  • Declare the variable inside the class, but outside of any method. for Example:

    namespace WebApplication1
    {
        public partial class _Default : System.Web.UI.Page
        {
            private Dictionary<string, object> myDictionary;
    
            protected void Page_Load(object sender, EventArgs e)
            {
                myDictionary = new Dictionary<string, object>();
                myDictionary.Add("test", "Some Test String as Object");
            }
    
            protected void TextBox1_TextChanged(object sender, EventArgs e)
            {
                myDictionary.Add("TextBox1Value", TextBox1.Text);
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                TextBox1.Text = myDictionary["test"].ToString();
            }
        }
    }