2009-04-17 2 views
0

에로드 할 때 나는 폼이로드 될 때 txt 파일의 내용을 읽고 배열에 저장하기를 원하는 C# 어플리케이션을 만들고 있습니다. 그런 다음 폼의 버튼을 클릭하면 배열에 액세스하기 위해 버튼 클릭 이벤트를 원합니다. 버튼 클릭 이벤트에 배열을 전달하는 방법은 무엇입니까? 아래의 코드에서 "statusArray가 현재 컨텍스트에 존재하지 않습니다"라는 오류가 발생하며 버튼 클릭 이벤트에서 배열에 대한 참조와 관련이 있습니다. 내가 무엇을해야 하나? 양식에 멤버 변수로폼이 read txt 파일을 배열

수잔

private void btnCompleted_Click(object sender, EventArgs e) 
    { 

     for (int i = 0; i < statusArray.Count; i++) 
     { 
      if (statusArray[i].Equals("Complete")) 

       lstReports.Items.Add(statusArray[i-2]); 

     } 
    } 

    private void Reports_Load(object sender, EventArgs e) 
    { 
     // declare variables 
     string inValue; 
     string data; 
     ArrayList statusArray = new ArrayList(); 


     inFile = new StreamReader("percent.txt"); 

     // Read each line from the text file 

     while ((inValue = inFile.ReadLine()) != null) 
     { 
      data = Convert.ToString(inValue); 
      statusArray.Add(inValue); 

     } 

     // Close the text file 
     inFile.Close(); 


    } 

답변

2

스토어 ArrayList에 다음과 같이 :

private ArrayList statusArray = new ArrayList(); 

private void btnCompleted_Click(object sender, EventArgs e) { 

    for (int i = 0; i < statusArray.Count; i++) 
    { 
     if (statusArray[i].Equals("Complete")) 

      lstReports.Items.Add(statusArray[i-2]); 

    } 
} 

private void Reports_Load(object sender, EventArgs e) 
{ 
    // declare variables 
    string inValue; 
    string data; 

    inFile = new StreamReader("percent.txt"); 

    // Read each line from the text file 

    while ((inValue = inFile.ReadLine()) != null) 
    { 
     data = Convert.ToString(inValue); 
     statusArray.Add(inValue); 

    } 

    // Close the text file 
    inFile.Close(); 


} 
+1

이 항목도 비공개로 설정하는 것이 좋습니다. –

1

가 글로벌 클래스하게 Reports_Load(object sender, EventArgs e) 방법, 외부에서 ArrayList를 선언 이동합니다.

또한 찾을 수있는 List<string> (강력한 형식)

1

ArrayList에이 배열로 하지 같은 일이며, 나중에 닷넷 2.0을 사용하는 경우에 데이터를 저장하기 위해 더 나은 것 배열 목록은 악한입니다.

이렇게 실패한 이유는 arraylist의 범위가 Reports_Load()입니다. 수업 수준으로 이동하고 List<string>으로 신고하려고합니다.

또 다른 옵션은 이고, 배열이이면 파일 클래스 '.ReadAllLines() 메서드를 사용합니다.

private string[] status; 

private void btnCompleted_Click(object sender, EventArgs e) 
{ 
    for (int i = 2; i < status.Length; i++) 
    { 
     if (status[i] == "Complete") 
      lstReports.Items.Add(status[i-2]); 

    } 
} 

private void Reports_Load(object sender, EventArgs e) 
{ 
    status = File.ReadAllLines("percent.txt"); 
}