微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 当前上下文中不存在名称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声明为公共或其他内容?如果是这样,怎么办呢?

解决方法

您在构造函数中将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>)并通过属性绑定显示部分,那么我可能会比这种方法做得更好.这样你就可以得到所选择的项而不是选定的索引……没有必要像这样保留文本/值对.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐