2017-04-20 14 views
1

我有一個csv文件,並想計數2.柱多少次包含111C#CSV計數在文件中或在datagridview的一個指定的數據

csv文件具有46組分離器分離的列; 。

"first col" "second col" "....." 
    abc   111   a 
    abc   112   b 
    abc   113   c 
    abc   111   d 
    abc   112   e 
    abc   113   f 

我想算111 填補了第一DataGridView的FOM數據表。

 dgv.DataSource = dgv_table; 

     string[] raw_text = File.ReadAllLines("d:\\"+lb_csv.Text); 
     string[] data_col = null; 
     int x = 0; 

     foreach (string text_line in raw_text) 
     { 

      // MessageBox.Show(text_line); 
      data_col = text_line.Split(';'); 

      if (x == 0) 
      { 
       for (int i = 0; i <= data_col.Count() - 1; i++) 
       { 

        dgv_table.Columns.Add(data_col[i]); 
       } 
       //header 

       x++; 
      } 

      else 
      { 
       //data 

       dgv_table.Rows.Add(data_col); 
      } 

我找到了很多解決方案來算第二列指定的數據:111 但所有的時間我有問題。

  int xCount = dgv.Rows.Cast<DataGridViewRow>().Select(row => row.Cells["second col"].Value).Where(s => s !=null && Equals(111)).Count(); 

     this.lb_qty.Text = xCount.ToString(); 

但它給錯誤row.Cells [「第二欄」。價值

An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll 

Additional information: Column named second col cannot be found. 

有人可以幫助我如何解決這個問題,並得到所需要的結果呢?

+0

我不知道如何你沒有得到'dgv_table.Columns.Add(data_col [i])的錯誤;'data_col應該是一個'string []',並且沒有Add方法用於只接受一個字符串的Columns。 –

+0

除非dgv_table是一個DataTable,這對於瞭解這些內容非常有用。 –

+0

@BlakeThingstad我試着用'DataGridView˛'和'DataTable',但仍然沒有Zoltan的單詞...... :) – Nino

回答

1

我會嘗試將文件讀入DataTable,並將其作爲DataSource用於DataGridView

DataTable d_Table = new DataTable(); 

//fill the DataTable 
this.dgv_table.DataSource = d_Table; 

計數行至極包含111在第二列中,您可以選擇DataTable這樣的:

DataTable d_Table = new DataTable(); 

//fill the DataTable 

DataRow[] rowCount = d_Table.Select("secondCol = '111'"); 
this.lb_qty.Text = rowCount.Length.ToString(); 

或者你可以在foreach -loop做到這一點:

int count = 0; 

foreach(DataGridViewRow dgr in this.dgv_table.Rows) 
{ 
    if(dgr.Cells["secondCol"].Value.ToString() == "111") count++; 
} 
this.lb_qty.Text = count.ToString(); 
+0

親愛的Wudge,它給了無效的轉換,但id我這樣的mod比我得到空引用異常。 。int count = 0; (DataGridViewRow dgr in this.dgv.Rows) if(dgr.Cells [1] .Value.ToString()==「2581」)count ++; } this.lb_qty.Text = count.ToString(); – Zoltan

+0

第二列是否有任何記錄是空的?如果是的話,你可以改變如果這樣:if(dgr.Cells [1] .Value!= null && dgr.Cells [1] .Value.ToString()==「2581」)count ++;' – Wudge

0
int CountValues(string input, string searchedValue, int ColumnNumber, bool skipFirstLine = false) 
{ 
       int numberOfSearchedValue= 0; 
       string line; 

      using (StreamReader reader = new StreamReader (input)) 
      { 
       if(skipFirstLine) 
        reader.ReadLine(); 

       while ((line = reader.ReadLine()) != null) 
       { 
        if(line.Split(';')[ColumnNumber] == searchedValue) 
         numberOfSearchedValue++; 
       } 
      } 
     return numberOfSearchedValue; 
} 

編輯: StreamReader.ReadLine()讀取行,但另外,使用這種方法我們跳到第二線。如果沒有更多行,它將返回null,所以這是我們的結束條件。其他的代碼是可讀的,我認爲 :)
沒有測試過,所以要小心:)
在某些地方使用Trim()或ToUpperCase()可能是必要的(通常當您搜索時) 。

2

我建議你跳過使用DataGridView並在循環中使用計數器變量,如Arkadiusz建議。

如果你仍然想用DataTable的工作,計數值是這樣的:

int xCount = dgv_table.Rows.Cast<DataRow>().Count(r => r["second col"] != null && r["second col"].ToString() == "111"); 
+0

它給出返回:在System.Core.dll中發生類型爲「System.InvalidCastException」的未處理異常 其他信息:無法轉換類型爲「System.Data.DataRow」的對象以鍵入「System.Windows.Forms.DataGridViewRow」。 – Zoltan

+0

@Zoltan對不起,你的問題很難遵循...所以,你使用DataTable,而不是DataGridView?...在​​這種情況下,看看編輯答案 – Nino

+0

親愛的Nino,你有權利,我忘了一部分我從datatable填充到datagridview – Zoltan

0

您可以使用此方法的CSV保存到數組列表清單

public static List<string[]> readCSV(String filename) 
{ 
    List<string[]> result = new List<string[]>(); 
    try 
    { 
     string[] line = File.ReadAllLines(filename); 
     foreach (string l in line) 
     { 
      string[] value= vrstica.Split(','); 
      result.Add(value); 
     } 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine("Error: '{0}'", e); 
    } 
    return result; 
} 

每個陣列將代表一列,所以你可以簡單地找到任何使用LINQ或甚至循環的值的頻率:

foreach (var item in tmp[1].GroupBy(c => c)) 
       { 
        Console.WriteLine("{0} : {1}", item.Key, item.Count()); 
       } 
相關問題