Reputation: 460
I want to sort the records on different parameters like mobile no. ,registration date , etc
My form looks like
After entering the mobile no. when I click on search I get the following result :
Now I want to sort the records w.r.t registration date.
Here is my code for sorting the record:
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 am getting the error "Cannot perform 'Like' operation on System.DateTime and System.String. "
Any solutions ??
Upvotes: 4
Views: 465
Reputation: 25414
You can try the LINQ instead of RowFilter:
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();
The query with searched date text:
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 RowFilter of created dataView to perform other filters.
Upvotes: 0
Reputation: 33809
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 a datatable
DataTable dt = (aboveQuery).CopyToDataTable();
Upvotes: 0
Reputation: 4628
You have to convert your date to a string before using the like:
dt.Select("Convert(column1,System.String) like '2013'")
or rd.RowFilter = "Convert(column1,System.String) like " + SearchRegdate;
You can check the full syntax here: syntax reference
Upvotes: 1
Reputation: 56697
First of all I thinkg the syntax is wrong. What would come out of your statment is something like:
registration_date like <user sort expression> '%...%'
There may not be anything between the like
and the filter expression %...%
.
Also, the column registration_date
is a DateTime
- you can not compare it to a string
using like
- and this is what the error is saying. You could add a hidden computed column that contains the date as string and sort on that.
Upvotes: 0