Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

c# - The name XXXX does not exist in the current context

I have the following code:

public Form1()
{
    InitializeComponent();


    string strRadio = Utils.ReadFile(strTemp + @"
stations.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 the error is The name 'aRadio' does not exist in the current context. Which comes from MessageBox.Show(aRadio[(index+1)]);. Do I need to declare the aRadio as public or something? If so, how would this be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're declaring aRadio as a local variable within your constructor. You need to declare it as an instance variable, and just assign it a value within 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 + @"
stations.txt");
    aRadio = strRadio.Split(new string[] { "#" },
                            StringSplitOptions.RemoveEmptyEntries);

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

I wouldn't be surprised if you could do rather better than this approach though, by adding a custom object (or just a KeyValuePair<string, string>) to the list box and binding the display part through properties. That way you could get the selected item rather than the selected index... there's no need to keep text/value pairs like this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...