名称XXXX在当前上下文中不存在 [英] The name XXXX does not exist in the current context

查看:48
本文介绍了名称XXXX在当前上下文中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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)]);
}

现在错误是名称'aRadio'在当前上下文中不存在.来自 MessageBox.Show(aRadio [(index + 1)]); .我是否需要将 aRadio 声明为public或其他内容?如果是这样,该怎么办?

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?

推荐答案

您正在将 aRadio 声明为构造函数中的局部变量.您需要将其声明为 instance 变量,然后在构造函数中为其分配一个值:

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 + @"\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> )添加到列表框并绑定通过属性显示零件.这样,您可以获得选定的 item 而不是选定的索引...无需保留这样的文本/值对.

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.

这篇关于名称XXXX在当前上下文中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆