I know this is an old problem but I cannot figure out why.
I have 2 voids binding in 2 buttons GENERATE and SAVE:
private void btn_generate_Click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(textstarteddate.Text);
DateTime enddate = new DateTime (startdate.Year, 12, 31);
Int64 addedDays = Convert.ToInt64(textdaycount.Text);
string taskID = texttaskID.Text;
string machine = cb_machineID.Text.Trim();
string note = texttasknote.Text;
string runningtime = RMT.Text;
string period = cb_periodID.Text.Trim();
_dtdate.Columns.Add(new DataColumn("Maintenance Date", typeof(DateTime)));
_dtdate.Columns.Add(new DataColumn("TaskID", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Machine", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Note", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Period", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Running Time", typeof(String)));
_dtdate.Rows.Clear();
G1.DataBindings.Clear();
if (cb_typescheID.Text == "Fix Date")
{
do
{
_dtdate.Rows.Add(startdate.Date, taskID, machine, note, period);
startdate = startdate.AddDays(addedDays);
G1.Refresh();
//DateTime end = startdate;
}
while (startdate <= enddate);
}
G1.DataSource = _dtdate;
G1.Columns["Maintenance Date"].DefaultCellStyle.Format = "d";
}
and
private void btn_save_Click(object sender, EventArgs e)
{
if (cb_typescheID.Text == "Fix Date")
{
foreach (DataRow dr in _dtdate.Rows)
{
sqlstr = sqlstr + " INSERT INTO [PerformTask] (Year, Date, TasKID, MachineID, PerformStatus, ScheduleID, PeriodID) Values ('" + startdate.Year + "', '" + dr["Maintenance Date"].ToString() + "',";
sqlstr = sqlstr + "'" + texttaskID.Text.Trim() + "', '" + machine + "', 'RS_Open', '" + typeschedule + "', '" + period + "')";
G1.Columns["Maintenance Date"].DefaultCellStyle.Format = "d";
}
}
}
I tried every way to convert it to only Date (dd/MM/yyyy) but it still display on a DataGridView(G1) but when i try to save it into my datatable in SQL, its format is still "dd/MM/yyyy hh:mm:ss tt" no matter how i convert it. I have read to old topic about this problem, tried their ways but still cannot save the data the way I want.
Please help. Thank you.
You could add the Column as string:
_dtdate.Columns.Add(new DataColumn("Maintenance Date", typeof(String)));
and then format the date when adding a new row:
_dtdate.Rows.Add(startdate.Date.ToString("dd/MM/yyyy"), taskID, machine, note, period);
If I understand you correctly, your problem is not displaying the date in date format within the grid, but has to do with the format in SQL?
Is your database field date or datetime (assuming we are MS SQL Server)? If you do not need the time information, it is much better to change the field to date. It is much to be preferred to store dates as dates rather than as strings, since you can perform operations on them as dates, without having to cast. In general, you should never be concerned with the way your database formats values; it is up to your presentation layer to handle formatting; your database should just concern itself with the efficient storing of data, and not worry about how that data looks.
Related
Am trying to make a comparison of DateTime in xamarin, but it has failed to work , below is my code:
When the system date is equal to the time set by users , it Toasts a
message
DateTime dt = DateTime.Now.ToLocalTime();
string timeset = "11:37".Trim();
DateTime oDate = DateTime.ParseExact(timeset, "HH:mm", null);
System.Diagnostics.Debug.WriteLine(" System Time : " + dt + " Set Time : " + oDate);
if (dt==oDate)
{
StartService();
}
What might be more helpful is to use the difference between the two times:
var diffInSeconds = (dt - oDate).TotalSeconds;
So:
DateTime dt = DateTime.Now.ToLocalTime();
string timeset = "08:56".Trim();
DateTime oDate = DateTime.ParseExact(timeset, "HH:mm", null);
System.Diagnostics.Debug.WriteLine(" System Time : " + dt + " Set Time : " + oDate);
var diffInSeconds = (dt - oDate).TotalSeconds;
System.Diagnostics.Debug.WriteLine(diffInSeconds);
if (Math.Abs(diffInSeconds) < 60)
{
System.Diagnostics.Debug.WriteLine("Equal");
}
This gives the difference to the nearest minute.
There are plenty of examples found via Google.
I have a problem with the filter of my datagridview. Currently, i'm applying 3 type of filter on date into my data (loaded by xml file) :
Month filter => This filter enable me to show all data relevant with the curent selected month
1 date filter => show all data which are associed to the current selected date
X dates filter => show all data which are associed to the current selected dates (31 max)
The filter is applied by seleting dates on a CalendarMonth control. The filter is actived on this method :
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
DateTime current_date = this.monthCalendar1.SelectionStart;
if (current_date.Month != this.old_Date.Month || current_date.Year != this.old_Date.Year)
{
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "DATE LIKE '*/" + current_date.ToString("MM/yyyy") + "'";
System.Console.WriteLine((this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter);
this.old_Date = current_date;
this.label_total.Text = this.calculateSum();
this.label_filter.Text = this.label_total.Text;
this.label_month.Text = current_date.ToString("MMMM (yyyy)");
}
else
{
if (this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy").Equals(this.monthCalendar1.SelectionStart.ToString("dd/MM/yyyy")))
{
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "DATE = '" + this.monthCalendar1.SelectionStart.ToString("dd/MM/yyyy") + "'";
this.label_filter.Text = this.calculateSum();
}
else
{
System.Console.WriteLine("DATE >= '" + current_date.ToString("dd/MM/yyyy") + "' AND <= '" + this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy") + "'");
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("DATE >= '" + this.monthCalendar1.SelectionStart.ToString("dd/MM/yyyy") + "' And DATE <= '" + this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy") + "'");
this.label_filter.Text = this.calculateSum();
}
}
}
The problem come when i have X selected dates. After selecting the date I have a strange bug. In fact, when i select 12/10 to 12/12 the filter show me the result of the october & november month ! The is no data for the december month a thoses dates.
Here a GIF of the problem :
the log for the filter say :
DATE >= '09/12/2015' AND <= '10/12/2015'
DATE >= '09/12/2015' AND <= '11/12/2015'
DATE >= '09/12/2015' AND <= '12/12/2015'
DATE LIKE '*/01/2016'
DATE LIKE '*/12/2015'
As we can see in the GIF the 2 other filters work fine. But the X selected dates didn't work like it is supposed to do ..
Anyone have an idea of the problem ?
For information :
Visual studio (community) 2015
C#
Windows Form
system in French (datetime in French, so => dd/MM/yyyy )
PS: sorry if the english ins't perfect.
Thank you.
What happens when you press December 21? If there's no results, then you should probably check the Locale of your DataTable and/or DataSet, that is the data source for your grid.
Is the result of the following code what you expected (dd/MM/yyyy)?
Console.WriteLine((this.dataGridView1.DataSource as DataTable).Locale.DateTimeFormat.ShortDatePattern);
I have found the bug ^^.
I used DATE column in String format and not in DateTime format. I have made all changes (in XML too) to work with DateTime value, and now the filter on X dates work fine !
Here the code of the new filtering method :
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
DateTime current_date = this.monthCalendar1.SelectionStart;
// we will identify if is the month/year who as changed or the day (to apply a filter on the data)
// month/year check
if (current_date.Month != this.old_Date.Month || current_date.Year != this.old_Date.Year)
{
// applying basic month & year filter (standard filter)
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "[DATE] >= '" + current_date.ToString("01/MM/yyyy") + "' AND [DATE] <= '"
+ DateTime.DaysInMonth(current_date.Year, current_date.Month).ToString() + current_date.ToString("/MM/yyyy") + "'";
System.Console.WriteLine((this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter);
this.old_Date = current_date;
this.label_total.Text = this.calculateSum();
this.label_filter.Text = this.label_total.Text;
this.label_month.Text = current_date.ToString("MMMM (yyyy)");
}
else
{
if (this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy").Equals(current_date.ToString("dd/MM/yyyy")))
{
//only one date is selected
// the day as changed
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "[DATE] = '" + current_date.ToString("dd/MM/yyyy") + "'";
System.Console.WriteLine((this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter);
this.label_filter.Text = this.calculateSum();
}
else
{
// more than 1 date is selected
(this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("[DATE] >= '" + current_date.ToString("dd/MM/yyyy") + "' AND [DATE] <= '" + this.monthCalendar1.SelectionEnd.ToString("dd/MM/yyyy") + "'");
System.Console.WriteLine((this.dataGridView1.DataSource as DataTable).DefaultView.RowFilter);
this.label_filter.Text = this.calculateSum();
}
}
}
Thx for the help #Arie ;)
I wanted to display all rows and columns in my DB between specific dates on an aspx web. However, dates are not recorded in date or date time format. And it seems it is not possible to convert them to date format. I try to do this like this;
public DataTable DisplayRecord()
{
var reqID = Request.QueryString["MyId"].ToString();
//Date parsing
String[] ids = reqID.Split('-');
String date1 = ids[0];
String date2 = ids[1];
String provider = ids[2];
SqlDataAdapter Adp = new SqlDataAdapter("SELECT * FROM flightLogs WHERE depDate_depTime=CONVERT(date,depDate_depTime,104) AND depDate_depTime BETWEEN CONVERT(date,'" + date1 + "',104)" +
" AND CONVERT(date,'" + date2 + "',104)", connection);
/*SqlDataAdapter Adp = new SqlDataAdapter("SELECT F.PNR, C.amount, F.provider, F.depDate_depTime FROM flightLogs F INNER JOIN companyLogs C ON F.PNR = C.PNR"+
" WHERE F.depDate_depTime=CONVERT(date,F.depDate_depTime,104) AND F.depDate_depTime BETWEEN CONVERT(date,'" + date1 + "',104)" +
" AND CONVERT(date,'" + date2 + "',104) AND F.provider='" + provider + "' ORDER BY F.depDate_depTime ASC", connection);*/
DataTable Dt = new DataTable();
Adp.Fill(Dt);
FlightMonitor.DataSource = Dt;
FlightMonitor.DataBind();
return Dt;
}
But i get this error;
"Conversion failed when converting date and/or time from character string."
Also data in my DB is shown like this;
origin destination deptDate_depTime PNR flightno provider
KBP AMS 18.09.2015 - 17:35:00 5RQZ43 PS712 Amadeus
ATH FRA 10.07.2015 - 12:30:00 ZFY8XW PS716 PGS
it is a bad idea to store datetime values in varchar columns as you can see.
if you need a specific format, then you should convert it while you are about to display that value to the users.
but to make things working for now, you can change your where clause from this:
depDate_depTime=CONVERT(date,depDate_depTime,104)
to this:
depDate_depTime = convert(datetime, left(depDate_depTime, 10) + ' ' + right(depDate_depTime, 8), 104)
I want to filter a Datatable and it works but if I search a DateTime I get a error.
Here is my code. What wrong have I done?
DataTable tb = DataBaseManager.GetRadiusDataTable(radiusconnectionstring, "marksullivan");
DataRow[] filteredRows = tb.Select("AcctStartTime LIKE '%" + searchstring + "%' OR AcctStopTime LIKE '%" + searchstring + "%' OR FramedIPAddress LIKE '%" + searchstring + "%'");
tb = filteredRows.CopyToDataTable();
this.ListView.DataSource = tb;
this.ListView.DataBind();
AcctStartTime:datetime
AcctStopTime :datetime
FramedIPAddress : varchar
The error: The Operation 'Like' could not to System.DateTime and System.String execute.
How can I do this?
Try like so DateComparision in RowFilter
string filter = $"DateFrom > '{daDateFrom}' AND DateTo <= '{daDateTo}'";
tb.Select(filter)
Or from DataRow filter Examples
Date values are enclosed within sharp characters # #. The date format
is the same as is the result of DateTime.ToString() method for
invariant or English culture.
[C#]
dataView.RowFilter = "Date = #12/31/2008#" // date value (time is 00:00:00)
dataView.RowFilter = "Date = #2008-12-31#" // also this format is supported
dataView.RowFilter = "Date = #12/31/2008 16:44:58#" // date and time value
The DayDate column in the database is of type DateTime & I'm passing a string formulated using a DateTimePicker in a form. The reader.HasRows always returns false!! I don't know what I'm doing wrong. Any help would be appreciated. The code that I used is below.
if (!this.con.IsConnected())
{
this.con.Connect();
}
this.cmd = new OleDbCommand("SELECT DayNo FROM [Calendar] WHERE DayDate = " + date + "", this.con.conObj());
this.reader = cmd.ExecuteReader();
this.reader.Read();
int dayNo;
if (this.reader.HasRows)
{
dayNo = int.Parse(reader[0].ToString());
}
else
{
throw new InfoException("The system could not locate the date in the system");
}
The problem is your comparing a Date value to a DateTime so in essence you could possibly be comparing values like this:
DayDate = "2011-12-18 14:22:54"
Date = "2011-12-18 00:00:00"
You need to truncate the time part from your DB dates, try something like this:
"SELECT DayNo FROM [Calendar] WHERE dateadd(dd, 0, datediff(dd, 0, DayDate)) = " + date
Or if using SQL Server 2008 you can do:
"SELECT DayNo FROM [Calendar] WHERE cast(DayDate As Date) = " + date