Sum of Last Column in Text File as DataSource of TextBox

Benemin

Member
Joined
Feb 17, 2010
Messages
12
Location
England
Programming Experience
Beginner
I have a text file that looks like this:

9,1,3,Half,2.20
9,2,9,Half,2.20
9,2,7,Full,3.40
9,2,7,Return,4.20
9,5,2,Half,2.20

Could someone show me how I would sum the last column, all of the numbers in bold, of this text file and then make the result as the DataSource of a Textbox? :D
 
Add a Dataset (untyped) to your form from Toolbox, add a Table to it, and add 6 columns to the table. Select DataType for the columns (three Int32, one String, two Single). For the 6th columns set Expression to "sum(Column5)" (without the quotes).

Add Textbox to form, in DataBindings property bind Text property to Column6 (navigate through > Other Data Sources, forms List Instances, DataSet1, Table1, Column6).

Now forms is configured and you can load data to the table:
VB.NET:
For Each line In IO.File.ReadAllLines("data.txt")
    Me.DataTable1.Rows.Add(line.Split(","c))
Next
 
Another option would be to use DataTable.compute to calculated the sum.

You can add the DataSet/DataTable as JohnH suggested. I just manually created one so you could see things a little clearer.

VB.NET:
        Dim ds As New DataSet
        Dim dt As New DataTable

        With dt.Columns
            .Add("Column1", GetType(Integer))
            .Add("Column2", GetType(Integer))
            .Add("Column3", GetType(Integer))
            .Add("Column4", GetType(String))
            .Add("Column5", GetType(Single))
        End With

        For Each line In IO.File.ReadAllLines("C:\Temp\Compute.txt")
            dt.Rows.Add(line.Split(","c))
        Next

        TextBox1.Text = dt.Compute("Sum(Column5)", "").ToString()

DataTable.Compute Method (System.Data)
 
I was thinking about that too, but without the binding you would need some event to tell whenever data is changed to assign the new Compute result to Textbox ("DataSource" binding to Textbox seemed to be the essence of this request). This could be simply solved by attaching the DataSet to a BindingSource and use its ListChanged event to recalculate.
 
Back
Top