Monday, June 15, 2015

vb.net - DataGridView to Datatable

Convert DataGridView Source to Datatable
***********************************

dim dt as New DataTable

dt = TryCast(dgv.DataSource, DataTable)

if, the datasource is BindingSource, then

use this:

dim bs as BindingSource

bs = TryCast(dgv.DataSource, BindingSource)
dim dv as New DataView
dv = bs.SyncRoot
dt = dv.ToTable


if, the Datasource is any of above, use this:


dt = New DataTable

Dim bs As New BindingSource
If TypeOf dgv.DataSource Is DataTable Then
 dt = TryCast(dgv.DataSource, DataTable)
Else
   bs = TryCast(dgv.DataSource, BindingSource)
   dv = New DataView
   dv = bs.SyncRoot
   dt = dv.ToTable
End If

Grouping Datetime Column by Date part only.

SELECT DATEADD(dd,(DATEDIFF(dd,0,CRETS)),0), COUNT(*)
FROM Table1
GROUP BY DATEADD(dd,(DATEDIFF(dd,0,CRETS)),0)

SELECT CAST(DATEDIFF(dd,0,CRETS) AS Datetime), COUNT(*)
FROM Table1
GROUP BY CAST(DATEDIFF(dd,0,CRETS) AS Datetime)


--Don't use this:
SELECT CONVERT(Datetime, CONVERT(NCHAR(10), CRETS, 121)), COUNT(*)
FROM Table1
GROUP BY CONVERT(Datetime, CONVERT(nchar(10), CRETS, 121))

Taken from: http://www.sqldisco.com/?p=6