Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Monday, May 12, 2014 1:43 PM
i have read similar posts regarding this topic and have set the datatype of a date column using the suggested code
.Columns(1).ValueType = GetType(DateTime) without success..
as others have noted, clicking the column header still results in the dates being sorted as strings.
i suspect the probelm stems from the fact that when i add rows to grid using .rows.add
i am adding a string array and regardless of the fact that i am defining the column datatype as DateTime
the grid still sorts by string...i do add the rows in descending order by date, but i would like to be able to allow the user to re-sort each column.
there HAS to be a way to accomplish this
All replies (2)
Tuesday, May 13, 2014 3:35 AM ✅Answered
Hi,
From your description, I known there is an issue regarding how to sort date column in DGV. The default behaviour of the DataGridView is that the columns can be sorted (i.e., by clicking on the header); in any case, you can force this behaviour by affecting the SortMode property. Regarding dates, you can add Date type columns to the given DataSource. Sample code for DataGridView1:
Dim dt As DataTable = New DataTable
dt.Columns.Add("col", GetType(Date))
dt.Rows.Add(New Date(2013, 2, 1, 10, 10, 0))
dt.Rows.Add(New Date(2012, 5, 10, 10, 10, 0))
dt.Rows.Add(New Date(2010, 5, 10, 10, 11, 10))
DataGridView1.DataSource = dt
DataGridView1.Columns(0).SortMode = DataGridViewColumnSortMode.Automatic 'Just to make sure
Rows in DataGridView1 will be sorted by clicking on the header of the first column. If you want to get all the records sorted from the start, you can sort the DataSource (dt); sample code:
Dim dataView As DataView = dt.DefaultView
dataView.Sort = "col asc"
DataGridView1.DataSource = dataView.ToTable() 'DGV sorted ascendently
Have a nice time!
Sincerely,
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.
Tuesday, May 13, 2014 6:00 AM ✅Answered
HI
Might be you are formatting date in sql query as string There fore it is consider as string at datagridview
In Order to sort datagridview on basis of date column use format property of datagridviewcoumn as
try
datagridview .Columns["DateColumnName"].DefaultCellStyle.Format = "yy/mm/dd";
Or
Dim Dc as new DatagridViewColumn
With DC
.DataPropertyName="DateColumnFromSql"
.HeaderText="Date"
.DefaultCellStyle.Format = "yy/mm/dd"
End DC
DatagridView1.Columns.Add(Dc)
Mark as answer if you find it useful
Shridhar J Joshi Thanks a lot