Sort in gridview c #

I want to sort entries by various parameters, such as mobile phone number., Date of registration, etc.

My form looks like enter image description here

After entering the mobile phone no. when I click on search, I get the following result:

enter image description here

Now I want to sort the registration date of the wrt record

Here is my code to sort the entry:

private void SearchDate() { DataTable rt = GetRecords(); DataView rd = new DataView(rt); string SearchRegdate = null; if (!String.IsNullOrEmpty(txtdate.Text)) { SearchRegdate = string.Format("{0} '%{1}%'", gvUser.SortExpression, txtdate.Text); } rd.RowFilter = "registration_date like " + SearchRegdate; gvUser.DataSource = rd; gvUser.PageSize = 30; gvUser.DataBind(); } 

Here I get the error "I can’t perform the" Like "operation on System.DateTime and System.String."

Any solutions

+4
source share
4 answers

You need to convert the date to a string before using:

 dt.Select("Convert(column1,System.String) like '2013'") 

or rd.RowFilter = "Convert (column1, System.String) as" + SearchRegdate;

You can check the full syntax here: syntax link

+1
source

First of all, I think the syntax is incorrect. What came out of your statement is something like:

 registration_date like <user sort expression> '%...%' 

There can be nothing between like and the filter expression %...% .

Also, the registration_date column is a DateTime - you cannot compare it to a string with like - and this is what the error says. You can add a hidden computed column that contains the date as a row, and sort by it.

0
source

You can try LINQ instead of RowFilter:

A simple example with DateTime:

Initialization:

 var table = new DataTable("Dates"); var dateColumn = new DataColumn("Date", typeof (DateTime)); table.Columns.Add(dateColumn); table.BeginLoadData(); table.LoadDataRow(new object[] {new DateTime(2000, 1, 1)}, true); table.LoadDataRow(new object[] {new DateTime(2000, 1, 2)}, true); table.LoadDataRow(new object[] {new DateTime(2001, 1, 1)}, true); table.LoadDataRow(new object[] {new DateTime(2002, 1, 1)}, true); table.EndLoadData(); 

Request with the search text for the date:

 var someDateText = "2000"; var dataView = (from row in table.AsEnumerable() let dateTime = row.Field<DateTime>(0) where dateTime.ToString().Contains(someDateText) orderby dateTime select row).AsDataView(); 

After that, you can also use the RowFilter of the created dataView to execute other filters.

0
source

Using Linq :

 var rows = (from r in rt.AsEnumerable() where SqlFunctions .StringConvert(r.Field<DateTime>("registration_date")).Contains("1") select r).ToList(); 

Or if you want to use datatable

 DataTable dt = (aboveQuery).CopyToDataTable(); 
0
source

All Articles