datetime conversion with specific format - c#

i want to filter the data from a datatable using dataview row filter Datatable having the column name month having like this "01-04-2012 00:00:00". I want to get the get the data using this format..
This is my partial code
dv1 = dtable.DefaultView;
DateTime start = new DateTime(DateTime.Now.Year, 4, 1,0,0,0);
dv1.RowFilter =Convert.ToString(start); //"Month = '04-01-2011 00:00:00'";
it returns the following error : Syntax error: Missing operand after '00' operator. I can't able to fix this error please help me to do this ...

You need to enclose the datetime value into #. You also have to say what column you want to compare with this value.
For example:
dv1.RowFilter = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,
"Date = #{0}#", start);
(where Date is the actual name of your datetime-column)
DataView.RowFilter Property
Using the InvariantCulture Property

Looking at the code, you are missing the name of the column you would want to filter on.
For example:
dv1.RowFilter = string.Format("PurchaseDate = '{0}'", Convert.ToString(start));
The assumption is that PurchaseDate is the date inside the view, the data is to be filtered using.

Related

DateOnly SQL Server type gets converted to TimeStamp in DataSet then in GridView unexpectedly [duplicate]

I have a GridView and I want to export it to Word. I want to change the format of one column to datetime format ("dd.MM.yyyy")
var grid = new GridView { DataSource = dt};
grid.DataBind();
In *.aspx page this is very easy, it looks like in the example below:
<asp:boundfield datafield="My_Date_Column"
dataformatstring="{0:dd.MM.yyyy}"
htmlencode="false" />
I want change format from c#, how to do this?
If you want to alter the format of a column of a GridView from CodeBehind
Add a RowDataBound to your grid view.
Then in the GridView_RowDataBound(object sender, GridViewRowEventArgs e) method, you'll be able to access e which will provide you with access to the individual cells of that row where you can specify a formatter.
Here's an example of using the RowDataBound event
http://forums.asp.net/p/1589807/4025153.aspx
String.Format("{0:dd.MM.yyyy}", myDateTimeInstance);
I think the format of column is based in system current date time format.
But when converting to string you can do so
String str = dt[RowNumber][ColumnName].ToString("dd.MM.yyyy");
DateTime dt = DateTime.Now;
String formated = dt.ToString("dd.MM.yyyy");
OR
String formated = String.Format("{0:dd.MM.yyyy}", dt );
DateTime dt = DateTime.Now;
string formated = dt.ToString("dd.MM.yyyy");
Possible formats are shown in this MSDN article.
In case you want to format the entire column then it would be better if you can set the property for your concerned column
gridview1.Columns[columnIndex].DataFormatString ="{0:dd.MM.yyyy}";
I think you will need to cast the column as BoundField to access the property.

How to Take Dynamic datatable last row is in first row order like that all rows in asp.net

I have created,
DataTable date= new DataTable();
date.Columns.Add("datenmoth");
and made fill the column name "Month" with date as
Month(Column name)
05-oct-2014
06-Nov-2014
02-Dec-2014
02-jan-2015
01-feb-2015
20-mar-2015
and made fill my dynamic table
Now, i want this dynamic table data to be Reverse order
i need result in: based on month and year taking reverse order
Month(Column name)
20-mar-2015
01-feb-2015
02-jan-2015
02-Dec-2014
06-Nov-2014
05-oct-2014
Thank you.
Don't fill this table with strings but with DateTimes. If you use string as column-type you always have to convert it to a DateTime. Like here:
var dateInReversedOrder = date.AsEnumerable()
.OrderByDescending(r => DateTime.Parse(r.Field<string>("datenmoth")))
.CopyToDataTable();
That works but is inefficient and prone to localization issues (in future).
Sample data and (desired) result after sorting in descending order:
DataTable date = new DataTable();
date.Columns.Add("datenmoth");
date.Rows.Add("05-oct-2014");
date.Rows.Add("20-mar-2015");

C# DataView Filter expression DateTime format

I'm defining a filter on a DataGridView on a DateTime column as follow:
BindingSource.Filter = "Column = '2016-05-26'"
Obviously the equality is not correct as the Column is expressed with the timestamp.
Then, I would like to convert the datetime during the evaluation and write it as:
BindingSource.Filter = "convert(Date, [Column]) = '2016-05-26'
But it doesn't work?
I would like to avoid to write:
BindingSource.Filter = "Column > '2016-05-25' AND Column < '2016-05-25'"
What is the best way to do that?
Thanks a lot

How to filter date values in datagrid

I can't filter a date value in my datagrid. Here is my code:
DataTable dbdataset;
DataView DV = new DataView(dbdataset);
DV.RowFilter = string.Format("Data LIKE '%{0}%'", textBox1.Text);
dataGridView1.DataSource = DV;
I always get this error:
Unable to Perform Operation 'Like' on System.DateTime and System.String
Please can someone help me?
You cannot use the LIKE operator on DateTime Data Type. Try using the equal operator.
DV.RowFilter = string.Format("Data = '{0}'", textBox1.Text);
But, be careful of what's inside textBox1.Text. It must be convertible to a DateTime Data Type. Remember also that DateTime has a Time part also, not just a Date part.
Or you may want to try this to filter all rows in a specific day:
DateTime dt = Convert.ToDateTime(textBox1.Text);
DV.RowFilter = string.Format("Data > '{0}' AND Data < '{1}'", dt.AddDays(-1).ToString("yyyyMMdd"), dt.AddDays(1).ToString("yyyyMMdd"));
Obviously field Data is from type Datetime and you can not perform Like on it. You can use:
DV.RowFilter = string.Format("Data = '{0}'", textBox1.Text);
Also you have possibility with =, >=, <=.
Also please change the field name to Date !
You can try something like that in LINQ
CultureInfo invC = CultureInfo.InvariantCulture;
var query= from myRow in dataTable.AsEnumerable()
where myRow.Field<DateTime>("Date").ToString(invC).Contains("mm/dd/yyyy")
select myRow;
// the date should be in format months/days/year -> Example 23 January 2014 is 01/23/2014
DataTable newTable= query.CopyToDataTable<DataRow>();
DV.RowFilter = string.Format("Data >= '{0}'", textBox1.Text);
will work if your column is a datetime in the database. This will return records at or newer than the specified date. Switch the sign to < if you're looking for records older than that date.

formatting datetime column in a DataSet

I have a dataset that is populated by reading excel file. The dataset stores the data from the excel.
The date in the dataset in in the format 2\2\2009 12:00:00 AM but i need the data format converted to 2\2\2009 .
I want to change the format of all the data in that particular column.
Here's one way:
foreach (DataRow row in yourDataTable)
{
DateTime dt = DateTime.Parse(row["Date"].ToString());
row["Date"] = dt.ToShortDateString();
}
This is assuming that the "Date" column is just a text field rather than already a DateTime field.
You can customize the output using a pattern if it is a DateTime object to the format you wanted, "2\2\2009".
string output1 = dt.ToString(#"mm\\dd\\yyyy");
string output2 = dt.ToString("mm/dd/yyyy"); //did you mean this?
A DateTime value or column has no format. It's just binary data.
Where do you want the formatted output to appear? That's where you should apply a format string. For instance, if you wanted it to appear in a column of an ASP.NET DataGrid, then you would set the DataFormatString property of the BoundColumn to "mm/dd/yyyy".
Try this. It will work
var result = from a in ds.Tables[0].AsEnumerable()
select new[] { Convert.ToDateTime(a[0]).ToString("dd/MM/yyyy") };

Categories