2016-02-16 63 views
0

我工作的家庭作業,我已經打了一個絆腳石努力研究信息讀取。我最大的問題是,我可以在datagrid或者CSV文件上找到很多信息,但不是真正的兩個在一起。數據網格爲vb.net,從CSV

我的目標是添加,然後我平均DataGrid的14列我從一個CSV文件中讀取後(在buttonclick1事件),並把該平均到一個標籤。我的第14列是在字符串中,並且具有該特定列的$#,###值。

現在,我的button1 click事件除了提出錯誤告訴我索引超出範圍,它必須是非負數並且小於集合的大小之外什麼也不做。

所以,我意識到這是補救的絕大多數人,但我只是在關於如何進行的徹底喪失。

Public Class frmMain 
    Dim rowContents As String 
    Dim cellContents(20) As String 
    'closes stuff 
    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click 
     Me.Close() 
    End Sub 

    Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click 
     DataGridView1.ColumnHeadersVisible = True 
     Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("F:\1TrevorProjects\MedicalCSV\MedicalProviders.csv") 
      MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited 
      MyReader.SetDelimiters(",") 
      Dim currentRow As String() 
      While Not MyReader.EndOfData 
       Try 
        currentRow = MyReader.ReadFields() 
        DataGridView1.Rows.Add(currentRow) 
        'Dim currentField As String 
        'For Each currentField In currentRow 
        'MsgBox(currentField) 
        'Next 
       Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException 
        MsgBox("Line" & ex.Message & "is not valid and will be skipped.") 

       End Try 
      End While 
      MyReader.Close() 
     End Using 
    End Sub 


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     Dim total As String = 0 
     For i As Integer = 0 To DataGridView1.RowCount - 1 
      total += DataGridView1.Rows(i).Cells(14).Value 
     Next 
     TextBox1.Text = total 
    End Sub 
End Class 
+0

的事情是,CSV中包含的所有字符串數據。我會傾向於創建一個帶有類型列的DataTable(即一個數字將存儲在Int32列中)。將行添加到該行,然後將DataTable綁定到DataGridView(== DataGrid ???)。迭代數據表以添加**數字**很容易。順便說一句,有沒有錯誤,或者它不工作,因爲你想要?什麼問題 – Plutonix

+0

哦,對不起,我會更新。 Button1_Click不做任何事情。我真的只是想找到代碼想法來取代特定的代碼。 我編輯了CSV,只在我想添加在一起的列中有數字數據,並且已經更改了列標題(如果這就是您指的是什麼?) 我可以更多地將兩者綁定在一起。我沒有看過或想過這個想法。謝謝!此外,感謝您修復我的格式! –

+0

您是否在設計器中添加了DGV列? (它甚至是DGV?)「拋出一個突破」是什麼意思?有沒有錯誤? – Plutonix

回答

0

兩件事情:

  • 如果DGV有AllowUsersToAddRows爲真,你的行循環將遍歷一個太多行,並拋出一個NullReferenceException
  • 如果目標列#14,細胞計數基於零,因此您應該參考.Cell(13)的值。

您可以輕鬆地做計算,你填充DGV:

Dim theTotal As Int32 
Dim rCount As Int32 
... 
DataGridView1.Rows.Add(currentRow) 
theTotal += Convert.ToInt32(currentRow(13)) 
rCount += 1 

然後,當循環結束:

Dim theAvg = (theTotal/rCount) 

如果數據在CSV作爲格式的貨幣(」 $ 123,45「),用這個代替:

theTotal += Decimal.Parse(currentRow(13), NumberStyles.Currency) 

通常情況下,升的應用程序,你必須做一些事情的數據,如導入到數據庫中,添加的cols,下降的cols等。在這種情況下,我會避免直接填充DGV和使用DataTable。特別是,如果代碼將不得不在循環中從字符串中解析格式化的貨幣。

這似乎矯枉過正了這一點,雖然。