2016-05-17 59 views
-2

從用戶在文本文件中我存儲的數據的分隔符,這是我的代碼做這個如何使用c#在XML文件中存儲來自txt文件的數據?使用

Student std = new Student(); 
dataGridView1.Rows.Clear(); //to clear the dataGridView Before showing the data 
dataGridView1.Refresh(); 
List<Student> students = new List<Student>(); 
using (StreamReader sr = new StreamReader(txt_path.Text)) 
{ 
    int x = 0; 
    while (sr.Peek() >= 0) 
    { 
     string str; 
     string[] strArray; 
     str = sr.ReadLine(); 

     strArray = str.Split('@', '#'); 
     Student s = new Student(); 
     s.ID = int.Parse(strArray[0]); 
     s.Name = strArray[1]; 
     s.Address = strArray[2]; 
     s.Phone = strArray[3]; 

     DataGridViewRow row = new DataGridViewRow(); 
     row.CreateCells(dataGridView1); // this line was missing 
     row.Cells[x].Value = s.ID; 
     row.Cells[++x].Value = s.Name; 
     row.Cells[++x].Value = s.Address; 
     row.Cells[++x].Value = s.Phone; 

     dataGridView1.Rows.Add(row); 
     students.Add(s); 
     x = 0; 
    } 
} 

這裏的問題,畢竟我的數據存儲在文本文件,然後我想保持它像XML文件「中圖片「。

enter image description here

我試過,但我在這張照片未能像

enter image description here

這是我做的Seconde系列圖片

  try 
     { 
      List<Student> students = new List<Student>(); 
      using (StreamReader sr = new StreamReader(txt_path.Text)) 
      { 

       string xmlc = string.Empty; 
       while (sr.Peek() >= 0) 
       { 
        string str; 
        string[] strArray; 

        str = sr.ReadLine(); 

        if (!string.IsNullOrWhiteSpace(str) && !str.StartsWith("#")) 
        { 
         xmlc += str; 
         strArray = xmlc.Split('@', '#'); 
         saveXml.saveData(xmlc, "data.xml"); 
         saveXml.saveData(strArray, "data.xml"); 
        } 

        Student s = new Student(); 
        s.ID = int.Parse(strArray[0]); 
        s.Name = strArray[1]; 
        s.Address = strArray[2]; 
        s.Phone = strArray[3]; 




        students.Add(s); 


       } 
      } 
     } 

     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

text file

+1

你能告訴我們用於創建/寫入'Xml'的代碼嗎? –

+0

@HariPrasad我編輯了我的問題。 –

+0

@FelicePollano,但在dataGridview和文本文件中存儲數據 –

回答

0
代碼

它有點不清楚,看你的代碼我假設你想讀一個文本文件並生成一個Xml文件。

你可以做這樣的事情。

var students = File.ReadLines(txt_path.Text) 
    .Select(line=>line.Split('@', '#') 
    .Select(x=> new Student() 
       { 
        ID = int.Parse(x[0]), 
        Name = x[1], 
        Address = x[2], 
        Phone = x[3] 
       }) 
    .ToList(); 

一旦你獲得學生的名單,你可以使用LinqXml並創建一個XML文件。

XElement element = 
    new XElement("Students", 
     (from student in students 
      select new XElement("Student", 
       new XElement("ID", student.ID), 
       new XElement("Name",student.Name), 
       new XElement("Address", student.Address), 
       new XElement("Phone",student.Phone) 
      ) 
     ) 
    ); 

element.Save(outputfile); 

最後但並非最不重要,你可以使用List<Student>作爲綁定源到DataGridView

dataGridView1.DataSource new BindingSource(new BindingList<Student>(students); 

檢查這demo你會知道這是如何工作的。

相關問題