2016-01-18 33 views
-3

文本文件中的數據看起來象下面這樣:文本文件作爲數據源,以顯示GridView的數據

FacilityID:12787 FacilityName:ACME醫療中心FacilityLocation:XYZ

FacilityID:27875 FacilityName:醫療中心FacilityLocation:KH

private void ReadFile(string fileName) 
     {    
      var rows = System.IO.File.ReadAllLines(fileName); 
      Char[] separator = new Char[] { ':' }; 
      DataTable tbl = new DataTable(fileName); 
      if (rows.Length != 0) 
      { 
       foreach (string headerCol in rows[0].Split(separator[0])) 
       { 
        tbl.Columns.Add(new DataColumn(headerCol)); 
       } 
       if (rows.Length > 1) 
       { 
        for (int rowIndex = 1; rowIndex < rows.Length; rowIndex++) 
        { 
         var newRow = tbl.NewRow(); 
         var cols = rows[rowIndex].Split(separator); 
         for (int colIndex = 0; colIndex < cols.Length; colIndex++) 
         { 
          newRow[colIndex] = cols[colIndex]; 
         } 
         tbl.Rows.Add(newRow); 
        } 
       } 
      } 
     } 

要添加上述代碼寫入數據表中的數據。 但它沒有正確填充。 「的DataTable錯誤地填充」

FacilityID:12787 
FacilityName:ACME Medical Center 
FacilityLocation:XYZ 
FacilityID:27875 
FacilityName:Medical Center 
FacilityLocation:kh 

我應該如何修改代碼的數據表中應填寫類似下面

FacilityID FacilityName  FacilityLocation 
    12787 ACME Medical Center XYZ 
    27875 Medical Center  kh 
+0

問題是什麼? (減去拼寫錯誤,目前爲止沒有問題) – Artyom

+0

Artyom:請檢查我是否已更新quetion..My quetion是從文本文件中讀取數據並將其顯示在gridview上 – John

+0

不明白這個問題。這樣做。有什麼問題? – Artyom

回答

0
private string GetID(string str) 
    { 
     if (!string.IsNullOrEmpty(str.Split(':')[1])) 
     { 
      return str.Split(':')[1].Replace("FacilityName", string.Empty); 
     } 
     return string.Empty; 
    } 

    private string GetName(string str) 
    { 
     if (!string.IsNullOrEmpty(str.Split(':')[2])) 
     { 
      return str.Split(':')[2].Replace("FacilityLocation", string.Empty); 
     } 
     return string.Empty; 
    } 

    private string GetLocation(string str) 
    { 
     if (!string.IsNullOrEmpty(str.Split(':')[3])) 
     { 
      return str.Split(':')[3]; 
     } 
     return string.Empty; 
    } 


    private string Button Click() 
    { 
     string rows = "FacilityID:12787 FacilityName:ACME Medical Center FacilityLocation:XYZ"; 
     DataTable tbl = new DataTable("test"); 
     if (rows.Length != 0) 
     { 
      tbl.Columns.Add("FacilityID"); 
      tbl.Columns.Add("FacilityName"); 
      tbl.Columns.Add("FacilityLocation"); 
      var newRow = tbl.NewRow(); 
      newRow[0] = GetID(rows); 
      newRow[1] = GetName(rows); 
      newRow[2] = GetLocation(rows); 
      tbl.Rows.Add(newRow); 
      dataGridView1.DataSource = tbl.DefaultView; 
     } 
    } 
+0

你的代碼的一點解釋不會傷害任何人。 – croxy

+0

在我的示例中,我使用了字符串。但你可以像從文件中讀取一樣進行更改。列名是恆定的,沒有改變,你可以使用上面的這個。 「:」分裂確定。但分裂後的問題,你會得到實際的價值+下一列名稱。所以在這裏我從單元格值中刪除列名稱。 –