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.
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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With