我有以下代码:
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)]);
}
现在错误为The name 'aRadio' does not exist in the current context
。哪个来自MessageBox.Show(aRadio[(index+1)]);
。我是否需要将aRadio
声明为公开或其他内容?如果是这样,将如何做?
答案 0 :(得分: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]);
}
}
通过向列表框添加自定义对象(或只是KeyValuePair<string, string>
)并通过属性绑定显示部分,我不会感到惊讶。这样你就可以获得所选的项而不是所选的索引......没有必要像这样保留文本/值对。
答案 1 :(得分:2)
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 :(得分:1)
您要访问构造函数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)]);
}
}
答案 3 :(得分:-3)
System.StringSplitOptions.RemoveEmptyEntries:以这种方式键入将解决您的问题。
不要问我为什么我知道它是这样运作的。