Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...