为什么会出现"The name x does not exist in the current context"错误?

3

我遇到了以下错误:

错误1:当前上下文中不存在“myList”名称

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            List<string> myList = new List<string>();
            myList.Add("Dave");
            myList.Add("Sam");
            myList.Add("Gareth");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (string item in myList)
            {
               listView1.Items.Add(item);
            }
        }
    }
}

这是一个非常简单的例子,实际的应用程序会更多地使用类,但我不明白为什么button1_click事件处理程序无法看到数组列表。


1
'listView1' 列表的声明在哪里? - superpuccio
@superpuccio - listView1列表只是我拖放到窗体上的一个控件。我需要声明它吗? - Ows
1个回答

3
根据您上面的评论,错误是:“当前上下文中不存在'myList'”,对吗?问题在于myList被声明在form1()方法内部,而您正在尝试从另一个方法(button1_click()方法)访问它。您必须将列表声明为类变量,放在方法外部。尝试这样做:
namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        private List<string> myList = null;

        public Form1()
        {
            InitializeComponent();
            myList = new List<string>();
            myList.Add("Dave");
            myList.Add("Sam");
            myList.Add("Gareth");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (string item in myList)
            {
               listView1.Items.Add(item);
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接