Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting "The name x does not exist in the current context"?

Tags:

scope

c#

I'm getting the following error:

Error 1 The name 'myList' does not exist in the current context

Code is as following:

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

It's a very simple example and a real world application would make more us out of classes, but I don't understand why the button1_click event hander can't see the array list.

like image 295
Ows Avatar asked Dec 06 '25 23:12

Ows


1 Answers

According to your comments above the error is: "The name 'myList' does not exist in the current context", right? The problem is that myList is declared inside the form1() method and you are trying to access it from another method (the button1_click() method). You must declare the list outside the method, as an instance variable. Try something like:

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);
            }
        }
    }
}
like image 167
matteopuc Avatar answered Dec 09 '25 13:12

matteopuc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!