Home > Net >  How to make public array or list in winform
How to make public array or list in winform

Time:03-26

I am exercising Listbox in winforms C# and I tried to make a public array or list to use in any control, In the example I am trying to filter a listbox depending on textbox1, and it works fine, but I need to mention the array twice once in Form1_Load to fill the listbox and the other on
textBox1_TextChanged to filter the items, What I need to do is to make a public array and mention it in any control, So I put my array in Public Form1() but it did not work.

  public Form1()
    {
        InitializeComponent();
           
            string[] Arry = new string[3];
            Arry[0] = "USA";
            Arry[1] = "Germany";
            Arry[2] = "United Kingdom";
                   
        
        
    }

    private void Form1_Load(object sender, EventArgs e)
    {
                  
        listBox1.Items.AddRange(Arry);
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        listBox1.Items.Clear();


        foreach (string str in Arry) 
    {
        if (str.StartsWith(textBox1.Text, StringComparison.CurrentCultureIgnoreCase))
        {
            listBox1.Items.Add(str);
        }
    }
}

It throws the error "Error 1 The name 'Arry' does not exist in the current context ", I tried to make a public void in class but did not work either,

CodePudding user response:

Like you said, move it out to class/form level:

private string[] Arry = new string[3];

public Form1()
{
    InitializeComponent();
       
    Arry[0] = "USA";
    Arry[1] = "Germany";
    Arry[2] = "United Kingdom";   
}
  • Related