我有以下代码:
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)]);
}
Run Code Online (Sandbox Code Playgroud)
现在错误是The name 'aRadio' does not exist in the current context.哪个来自MessageBox.Show(aRadio[(index+1)]);.我是否需要宣布aRadio公开或其他什么?如果是这样,怎么办呢?
Jon*_*eet 21
您在aRadio构造函数中声明为局部变量.您需要将其声明为实例变量,并在构造函数中为其赋值:
// 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]);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你能比这种方法做得更好,通过KeyValuePair<string, string>在列表框中添加一个自定义对象(或只是一个)并通过属性绑定显示部分,我不会感到惊讶.这样你就可以得到所选择的项而不是选定的索引......没有必要像这样保留文本/值对.