Dataview rowfilter invalid datetime string - c#

I'm struggling with the following. I have a DataTable with dates in it. Dates that can contain several time rows. Now I want to click on a date on the calender and it will put the times records from that day in a listbox so I can then select the time.
I'm stuck and googled around but I'm blind at this point.
The datatable output in gridview:
Datum
-----------------
22-09-14 13:05:00
22-09-14 13:05:18
23-09-14 13:05:36
23-09-14 13:05:54
23-09-14 13:06:12
21-09-14 14:00:01
21-09-14 15:00:01
21-09-14 16:00:01
21-09-14 17:00:01
The code in the calander SelectionChanged event:
// Create datatable
DataTable dt = new DataTable();
string FileName = "C:\\ProjectName\\data\\data.dat";
var lines = File.ReadAllLines(FileName);
// Make date column
dt.Columns.Add("Datum", typeof(DateTime));
// add rows
for (int i = 2; i < lines.Count(); i++)
{
DataRow dr = dt.NewRow();
string[] values = lines[i].Split(new char[] { ',' }).Select(x => x.Replace("\"", "")).ToArray();
for (int j = 0; j < values.Count() && j < 1; j++)
dr[j] = values[j];
dt.Rows.Add(dr);
}
// Convert selected date
string currentDate = e.SelectedDates.Count - 1 >= 0 ? e.SelectedDates[e.SelectedDates.Count - 1].Date.ToString("dd-MM-yyyy") : "none";
// Print selected date to see format
Label1.Text = currentDate;
// Create dataview and apply filter
DataView dv = new DataView(dt);
dv.RowFilter = "Datum = #" + currentDate + "#";
dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
dv.Sort = "Datum DESC";
// dataview to listbox
lbSource.DataSource = dv;
lbSource.DataTextFormatString = "{0:dd-MM-yyyy HH:mm}";
lbSource.DataTextField = "Datum";
lbSource.DataValueField = "Datum";
lbSource.DataBind();
The dv filter gives me:
String was not recognized as a valid DateTime.
Debugging stops with the following line and gives the "String was not recognized as a valid DateTime.":
dv.RowFilter = "Datum = #" + currentDate + "#";
currentdate comes with the correct date: 22-09-2014 (dd-MM-yyyy)
If someone could help me out, thanks a lot :)

Basically the .rowfilter compare takes the date as Mm/dd/yyyy as comparison. It will see 20/10/2018 as an invalid date. It will work for day being lower than 12.
So in your datatable, the date is stored as dd/mm/yyyy.
Unless you change the date storage format to mm/dd/yyyy, I don't think you can rowsfilter.

Related

c# How to update variable value in loop

I've try to loop and from the below code, The problem is when it loop back to “IEnumerable selectedRows =”. The value of DateStart and DateEnd remain the same “9/1/2003 2:00:00” and “9/1/2003 2:59:00” respectively as its initial value. Why the “IEnumerable selectedRows =” do not update the DateTime value? Please help and thank you.
IEnumerable<DataRow> selectedRows =
dtData
.AsEnumerable()
.Where(row =>
row.Field<DateTime>("Date") >= DateStart
&& row.Field<DateTime>("Date") <= DateEnd);
foreach (DataRow row in selectedRows)
{
//Do some stuffs
}
//store the result in DataTable
DataRow dtDataRowResult = dtDataResult.NewRow();
dtDataRowResult[0] = DateStart;
dtDataRowResult[1] = result1;
dtDataRowResult[2] = result2;
dtDataResult.Rows.Add(dtDataRowResult);
//when code go this line below,
//it should be added one hour from the previous hour,
//so now it is “9/1/2003 3:00:00”
DateStart = DateStart.AddHours(1);
//and the DateEnd should be added to “9/1/2003 3:59:00”
DateEnd = DateStart + TimeSpan.FromMinutes(59);
//The problem is when it loop back to
//“IEnumerable<DataRow> selectedRows =”.
//The value of DateStart and DateEnd remain the same
//“9/1/2003 2:00:00” and “9/1/2003 2:59:00” respectively
//as the initial value. Why the
//“IEnumerable<DataRow> selectedRows =” not updated the
//DateTime value? Please help and thank you.
The below is the screenshot image of the example code
Let me see if I've produced a [mcve] that demonstrates your problem:
DateTime dateTime = new DateTime(2023, 1, 9, 2, 0, 0);
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Date", typeof(DateTime));
DataRow dataRow = dataTable.NewRow();
dataRow[0] = dateTime;
dataTable.Rows.Add(dataRow);
Console.WriteLine($"{dateTime} == {(DateTime)dataTable.Rows[0][0]}");
dateTime += TimeSpan.FromMinutes(59.0);
Console.WriteLine($"{dateTime} != {(DateTime)dataTable.Rows[0][0]}");
When I run that I get this output:
2023/01/09 02:00:00 == 2023/01/09 02:00:00
2023/01/09 02:59:00 != 2023/01/09 02:00:00
The value in the DataTable does not update when I update the dateTime variable.
This is because when dateTime += TimeSpan.FromMinutes(59.0); is called the value in the variable dateTime is updated, but the variable stored in the DataTable is a copy of the original dateTime value. It's not linked in any way.
To make it update you would need to run this code:
dataTable.Rows[0][0] = dateTime;
Now we can see it is the same with this:
Console.WriteLine($"{dateTime} == {(DateTime)dataTable.Rows[0][0]}");
That produces:
2023/01/09 02:59:00 == 2023/01/09 02:59:00

DateTime format in SQL

I am having some problem when trying to format DateTime in Asp.net. I wanted the date to display as 18/1//2014 instead of 18/1/2014 12.00 AM. Here is the code:
DataTable dt = new DataTable();
dt.Columns.Add("totalQuantity");
dt.Columns.Add("deliveryDate");
for (int count = 0; count < catSumList.Count; count++)
{
DataRow dr = dt.NewRow();
dr["totalQuantity"] = catSumList[count].productQuantity;
dr["deliveryDate"] = catSumList[count].deliveryDate;
dt.Rows.Add(dr);
}
string[] deliveryDate = new string[dt.Rows.Count];
decimal[] totalQuantity = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
totalQuantity[i] = Convert.ToInt32(dt.Rows[i][0]);
deliveryDate[i] = dt.Rows[i][1].ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
}
lcCategory.Series.Add(new AjaxControlToolkit.LineChartSeries { Data = totalQuantity });
lcCategory.CategoriesAxis = string.Join(",", deliveryDate);
lcCategory.ChartTitle = string.Format(categoryName);
lcCategory.Visible = true;
However, it gives me an error message at this line:
deliveryDate[i] = dt.Rows[i][1].ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
The error message is No overload method ToString takes 2 arguments. I wonder is there any other way to format it? My data type for deliveryDate in database is DateTime. Thanks in advance.
Since you are working with DataTables which are weakly typed and not recommended to be used you will need to first cast to a DateTime before being able to apply any format:
deliveryDate[i] = ((DateTime)dt.Rows[i][1]).ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
The Rows property returns an object which you need to cast.
Use:
deliveryDate[i] = ((DateTime)dt.Rows[i[1]).
ToString("dd/M/yyyy",CultureInfo.InvariantCulture);

get datetime value from datagridview cells and change it to persian date at run time

I have a problem in DataGridView .
I fill DataGridView with a datable .
there are two columns that get date time value in DataGridView I want to change this value to Persian Date at run time what should I do?
You could fill another DataTable by using PersianCalendar:
DataTable table = new DataTable();
table.Columns.Add("Persian date 1");
table.Columns.Add("Persian date 2");
var persCal = new System.Globalization.PersianCalendar();
foreach(DataRow row in dataTable1.Rows)
{
DateTime dt1 = row.Field<DateTime>(0);
DateTime dt2 = row.Field<DateTime>(1);
int year1 = persCal.GetYear(dt1);
int month1 = persCal.GetMonth(dt1);
int day1 = persCal.GetDayOfMonth(dt1);
int year2 = persCal.GetYear(dt2);
int month2 = persCal.GetMonth(dt2);
int day2 = persCal.GetDayOfMonth(dt2);
string persDate1 = string.Format("{0}-{1}-{2}", year1, month1, day1);
string persDate2 = string.Format("{0}-{1}-{2}", year2, month2, day2);
table.Rows.Add(persDate1, persDate2);
}
Then use this as datasource.

How to Add GridView Columns Dynamically based on calender months

How can I add Gridview columns dynamically based on calender days?
The header of the grid should show dates 01/01/2013, 02/01/2013...and each column is a TemplateField with a Dropdownlist
I achieved this for the weekly view since the fields are constant (7 fields) but when it comes to the month view I cannot add 30 or 31 fields because I've coded in ASP not on code behind C#.
Can anybody give me some hints on how to create a month calendar in this way?
I already tried these links but it didn't help
http://geekswithblogs.net/dotNETvinz/archive/2010/08/03/adding-dynamic-rows-in-gridview-with-textbox-and-dropdownlist.aspx
http://bytes.com/topic/asp-net/answers/925328-how-display-selected-dates-database-calendar-control
You can try doing something like this:
DataTable dt = new DataTable();
DataColumn dcol = new DataColumn("ID", typeof(System.Int32));
dcol.AutoIncrement = true;
dt.Columns.Add(dcol);
int days = 0;
string selected_month = "JAN";
if (selected_month == "JAN" || selected_month == "MAR")
{ days = 31; }
else if(selected_month == "APR")
{ days = 30; }
for (int z = 1; z < days; z++)
{
dcol = new DataColumn(z.ToString(), typeof(System.String));
dt.Columns.Add(dcol);
}

How to search people by birthday?

I've found this way, is there any other simplier?
ClienteAdapter cliente = Cache.CacheManager.Get<ClienteAdapter>();
DataTable dt = cliente.GetDataTable();
DateTime dta = DateTime.Today;
String dia = dta.Day.ToString();
if (dta.Day < 10)
dia = '0'+dia;
String mes = dta.Month.ToString();
if (dta.Month < 10)
mes = '0'+mes;
String aniversario = String.Format("{0}-{1}", dia, mes);
dt = cliente.Get(dt, String.Format("WHERE dtNascCli LIKE '%{0}%'", aniversario));
if (dt.Rows.Count>0) {
String aniversariantes = "Aniversariantes do dia:\n";
for (int i = 0; i < dt.Rows.Count; i++)
{
aniversariantes += ((dt.Rows[i]["nmComprador"] != null) : dt.Rows[i]["nmComprador"] ? dt.Rows[i]["nmRazao"]) + "\n";
}
LINQ could get you started.
from DataRow dr in dt.Rows
where ((Date)dr["birthday"]).Month = Date.Today.Month && ((Date)dr["birthday"]).Day = Date.Today.Day
select dr;
That yields an IEnumerable<DataRow>, which you could iterate over with a foreach.
EDIT: Incorporated bemused's comment regarding previous years.
You could simplify this:
DateTime dta = DateTime.Today;
String dia = dta.Day.ToString();
if (dta.Day < 10)
dia = '0'+dia;
String mes = dta.Month.ToString();
if (dta.Month < 10)
mes = '0'+mes;
String aniversario = String.Format("{0}-{1}", dia, mes);
Into this:
String aniversario = DateTime.UtcNow.ToString("dd'-'MM");
// You *are* storing dates in UTC aren't you?
This doesn't change the fact that this isn't a good way to store or search for dates, but its a good place to start.
That's all I got, besides Jim Dagg's LINQ example.

Categories