2016-01-18 35 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

在我的示例中,我使用了字符串。但你可以像从文件中读取一样进行更改。列名是恒定的,没有改变,你可以使用上面的这个。 “:”分裂确定。但分裂后的问题,你会得到实际的价值+下一列名称。所以在这里我从单元格值中删除列名称。 –