2013-02-22 115 views
0

您是一個相當新手談到C#和我試圖讀出一個文本文件,然後將它分爲類與部分,但在哪裏申報他們的麻煩然後如何循環記錄。這裏是我的代碼試圖讀取文本文件到類然後循環通過

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

namespace Assignment_3 
{ 
    public partial class Form1 : Form 
    { 
     string s; 
     string ss; 
     int i = 1; 
     string infilename; 
     int num; 
     SortedList sList = new SortedList(); 
     int x = 0; 

     public Form1() 
     { 
      InitializeComponent(); 
      student myself = new student(); 
      infilename = "text.txt"; 
      StreamReader sr1 = new StreamReader(infilename); 
      sList.Clear(); 
      while ((s = sr1.ReadLine()) != null) 
      { 
       string[] strs = s.Split(','); 

       myself.firstname = strs[0]; 
       myself.middlename = strs[1]; 
       myself.surname = strs[2]; 
       myself.dob = DateTime.Parse(strs[3]); 
       myself.dob.ToString(strs[3]); 
       myself.sex = strs[4]; 
       ss = myself.dob.ToString("u"); 
       sList.Add(myself.firstname, myself); 

      } 
      sr1.Close(); 
      num = sList.Count; 
      student[] pArray = new student[num]; 
      string[] keys = new string[num]; 



      foreach (DictionaryEntry d in sList) 
      { 
       keys[x] = (string)d.Key; 
       pArray[x] = (student)d.Value; 
       x++; 
      } 
      if (i == 0) 
      {lblmessage.Text = "Already at the first record."; i = 1; } 
      if (i == num) 
      {lblmessage.Text = "Already at the last record.";i = num-1; } 

      lbllastname.Text = pArray[i].surname; 
      lblfirstname.Text = pArray[i].firstname; 
      lblsecondname.Text = pArray[i].middlename; 
      lbldob.Text = pArray[i].dob.ToString(); 
      lblsex.Text = pArray[i].sex; 

     } 

     private void btnlast_Click(object sender, EventArgs e) 
     { 
      i = num; 

     } 
     private void btnfirst_Click(object sender, EventArgs e) 
     { 
      i = 0; 
     } 

     private void btnnext_Click(object sender, EventArgs e) 
     { 
      i++; 

     } 

     private void btnprev_Click(object sender, EventArgs e) 
     { 
      i--; 
     } 


    } 
} 

和我的類文件

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Assignment_3 
{ 
    class student 
    { 
     public string firstname; 
     public string middlename; 
     public string surname; 
     public DateTime dob; 
     public string sex; 
    } 
} 

人有任何想法我在哪裏去錯了?我沒有錯誤,但發現文本字段不更新與新的記錄,然後當通過數組類持有正確數量的記錄和字段時,我覺得它將是非常明顯的東西,讓我不能把它放在手指上。

任何幫助將不勝感激。

+0

您還沒有告訴我們您收到哪些錯誤以及在哪裏? – 2013-02-22 18:50:05

+0

爲您在while循環中閱讀的每一行創建一個新學生:myself = new student(); – rene 2013-02-22 18:50:09

回答

0

您應該在for循環內創建student的新實例。因爲目前您只有一個學生課程實例,SortedList中的所有項目都指向同一個對象。