2014-06-18 2 views
2

나는 다음과 같은 오류를 받고 있어요 :"x는 현재 컨텍스트에 존재하지 않습니다"라는 이유는 무엇입니까?

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

코드는 다음과 같습니다 :

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

+0

@superpuccio - listView1 목록은 내가 폼에 드래그 한 컨트롤입니다. 그것을 선언해야합니까? – Ows

답변

2

위의 사용자 의견에 따르면 오류가 있습니다 : "이름 'myList'가 현재 컨텍스트에 없습니다." 문제는 form1() 메서드 내에서 myList이 선언되어 있고 다른 메서드 (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); 
      } 
     } 
    } 
} 
관련 문제