Name XXXX does not exist in the current context

I have the following code:

public Form1()
{
    InitializeComponent();


    string strRadio = Utils.ReadFile(strTemp + @"\rstations.txt");
    string[] aRadio = strRadio.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);    
    for (int i = 0; i < aRadio.Length; i += 2)
    {
       listBox.Items.Add(aRadio[i]);
    }

}

private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = listBox.SelectedIndex;
    MessageBox.Show(aRadio[(index+1)]);
}

Now a mistake The name 'aRadio' does not exist in the current context. What comes from MessageBox.Show(aRadio[(index+1)]);. Should I declare it aRadioas public or something else? If so, how will this be done?

+3
source share
4 answers

You declare aRadioas a local variable in your constructor. You need to declare it as an instance variable and just assign it a value inside your constructor:

// TODO: Give this a better name
private readonly string[] aRadio;

// TODO: Give your form a better name too
public Form1()
{
    InitializeComponent();

    // TODO: You might want to reconsider reading files in a GUI constructor, too
    // TODO: Use Path.Combine(strTemp, "rstations.txt" instead of concatenation
    string strRadio = Utils.ReadFile(strTemp + @"\rstations.txt");
    aRadio = strRadio.Split(new string[] { "#" },
                            StringSplitOptions.RemoveEmptyEntries);

    for (int i = 0; i < aRadio.Length; i += 2)
    {
       listBox.Items.Add(aRadio[i]);
    }
}

, , , ( KeyValuePair<string, string>) . , , ... , .

+21
   private string[] aRadio;

    public Form1() { 
      InitializeComponent();       
      string strRadio = Utils.ReadFile(strTemp + @"\rstations.txt");
      this.aRadio = strRadio.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
      for (int i = 0; i < aRadio.Length; i += 2)
      {
        listBox.Items.Add(aRadio[i]);
      }
    }

    private void listBox_SelectedIndexChanged(object sender, EventArgs e) {
      int index = listBox.SelectedIndex;
      MessageBox.Show(this.aRadio[(index+1)]);
    } 
+2

, form1,

//Define the variable as an attribute of class

private string[] strRadio;
public Form1()
{
        InitializeComponent();
        string strRadio = Utils.ReadFile(strTemp + @"\rstations.txt");
        aRadio = strRadio.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < aRadio.Length; i += 2)
        {
           listBox.Items.Add(aRadio[i]);
        }

    }

    private void listBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = listBox.SelectedIndex;
        MessageBox.Show(aRadio[(index+1)]);
    }
}
+1

System.StringSplitOptions.RemoveEmptyEntries: , .

, , .

-2

All Articles