|
-
Aug 13th, 2007, 09:31 AM
#1
Thread Starter
Hyperactive Member
[RESOLVED] [2005] Total of a column in a Datagridview
Hello,
I have a datagridview on my form which populates when the form is loaded.
As you can see by my code, one of the columns in this datagridview is "Hours".
Code:
Try
dsOvertime = Overtime.Get_Overtime()
Dim dv As DataView
dv = New DataView(dsOvertime.Tables(0))
dgvOvertime.DataSource = dv
dgvOvertime.ReadOnly = True
dgvOvertime.Columns("OvertimeID").Visible = True
dgvOvertime.Columns("Employee").Visible = True
dgvOvertime.Columns("OvertimeDate").Visible = True
dgvOvertime.Columns("Hours").Visible = True
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
I would like a textbox at the bottom to show the total of this "hours" column.
How do I do it please ?
I've been searching on here and on the following thread jmcilhinney has suggested a line of code, but it relies os the Datagridview being bound to a datatable.
http://www.vbforums.com/showthread.php?t=439382
As I don't know how to do this, I can't get any further.
Last edited by Jonny1409; Aug 13th, 2007 at 09:46 AM.
-
Aug 14th, 2007, 01:57 AM
#2
Re: [2005] Total of a column in a Datagridview
Your grid IS bound to a DataTable, although indirectly. The dataView is merely a window through which you view data in a DataTable.
I strongly suggest using a BindingSource every time you bind data to controls. Forget that DataView altogether. Add a BindingSource to your form and bind your DataTable to it, then bind it to the grid. You can now filter and sort the data in the grid using the BindingSource's Filter and Sort properties.
To get the value you're interested in you use the DataTable:
vb.net Code:
Dim totalHours As Double = CDbl(DirectCast(myBindingSource.DataSource, DataTable).Compute("SUM(Hours)", myBindingSource.Filter))
By using the filter you ensure that any rows filtered out by the BindingSource are not included in the aggregate.
Note that this is not magic on the part of the BindingSource. Even if you stuck with your current code you could still do it using the DataTable:
vb.net Code:
Dim view As DataView = DirectCast(myGrid.DataSource, DataView)
Dim totalHours As Double = CDbl(view.Table.Compute("SUM(Hours)", view.RowFilter))
It's almost the same code. The BindingSource offers numerous advantages when binding data though, so I suggest using it almost always.
-
Aug 14th, 2007, 08:38 AM
#3
Thread Starter
Hyperactive Member
Re: [2005] Total of a column in a Datagridview
Thank you very much jmc, I'll do as you suggest.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|