I have to 2 dropdownlists and I want to populate them with their values as hours from 1 to 24. Then I want to calculate the difference between the two selected values. If i choose in the first dropdown let's say the hour value as 12 AND second value as 16 then the difference will be 4.
How can I achieve that in c#?
I'm developing a asp.net web application coded in C#.
Below is the code of how I populate my dropdownlist:
DateTime Date = DateTime.Today;
DateTime Time = DateTime.Now;
ListItem item1 = new ListItem(Time.ToShortTimeString(),
Time.ToShortTimeString());
for (int i = 0; i <= 48; i++)
{
ListItem item2 = new ListItem(Date.ToShortTimeString(),
Date.ToShortTimeString());
droplist.Items.Add(item2);
if (Date.CompareTo(Time) < 0 && Date.AddMinutes(30).CompareTo(Time) > 0)
droplist.Items.Add(item1);
Date = Date.AddMinutes(60);
}
How can I assign values to my dropdown, values being the hours?
Instead of adding the date/time string to the drop down, you may add the DateTime value itself. The dropdown displays its members by calling ToString(). The disadvantage here: you are not able to use another time format like ToShortTimeString().
Another way is to use the DateTime.TryParse method to convert back before calculating.
Related
Here is my scenario: When I click an item from datagridview I want to check to see if the job such as fixing a computer is not going to happen at the same time as another event on my schedule. If one event is at 1pm on 6/14/20 I don't want to allow the user to be able to select another job that overlaps with that one. I actually want a minimum of an hour between events. Where do I start with this?
I have a datagridview that gets data from a Mysql table called jobs. It displays all of the details of the job (date, time, type of event, etc.). When I click on an item from the table it stores the data in string variables and opens another window to confirm the user's selection. For example JobType will get stored in a string called type, date will get stored in a string date, time will get stored in a string time. I want the check to occur before the confirmation window pops up.
This is a windows forms app in C#
Here is my code that i tried:
//convert date time that is selected from datagridview
DateTime dtselected = DateTime.Parse(date + " " + time);
//convert date time of each job
DateTime dtstored = DateTime.Parse(job.JobDateTime);
//subtract values
TimeSpan value1 = dtselected.Subtract(dtstored);
TimeSpan value2 = dtstored.Subtract(dtselected);
//set minimum difference between the two times to be 1 hour and 5 minutes
TimeSpan difference = new TimeSpan(0, 1, 5, 0, 0);
//check if two times overlap
if(value1 <= difference || value2 <= difference)
{
MessageBox.Show("Job times too close");
return;
}
I try to draw Chart via C# with table as picture.
However, as you can see A4 data in date: 7 and 8/6 should stay with same 7 and 8/6 X-Axis, abnormal here all of them left to 5 & 6/6 X-Axis. Could you help me to fix it.
for (int i = 0; i < 14; i++)
{
string productname = dataGridView1.Rows[i].Cells[0].Value.ToString();
string datetime = dataGridView1.Rows[i].Cells[2].Value.ToString();
int para = Convert.ToInt16(dataGridView1.Rows[i].Cells[1].Value);
if (chart_dashboard.Series.IndexOf(productname) != -1)
{
chart_dashboard.Series[productname].Points.AddXY(datetime, para);
chart_dashboard.ChartAreas[0].AxisX.Interval = 1;
}
else
{
chart_dashboard.Series.Add(productname);
chart_dashboard.Series[productname].Points.AddXY(datetime, para);
chart_dashboard.ChartAreas[0].AxisX.Interval = 1;
}
}
A common mistake.
string datetime = dataGridView1.Rows[i].Cells[2].Value.ToString();
This is wrong! If you add the x-values as strings they all are added as 0 and the Series can't align them to the proper slots on the X-Axis. So they get added from left to right sequentially..
Instead simply add the x-values as the DateTimes they are supposed to be!
So if the Cells contain DateTime values use:
DateTime datetime = (DateTime) dataGridView1.Rows[i].Cells[2].Value;
If they don't, convert them to DateTime
DateTime datetime = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value);
To control the x-values type set the XValueType for each series:
chart_dashboard.Series[yourSeries].XValueType = ChartValueType.DateTime;
To control the way the axis labels are displayed set their formatting:
chart_dashboard[ChartAreas[0].AxisX.LabelStyle.Format = someDateTimeFormatString;
To create a string like "Week 1" you would
set the XValueType to int16
add the x-value as the week numbers
format it like ..axis.LabelStyle.Format = "Week #0";
To extract the number from your data split by space and Convert.ToInt16 !
If one really needs to insert sparse x-values as strings one would have to insert a dummy DataPoint at each gap in a series.
Creating a dummy DataPoint is simple:
DataPoint dp = new DataPoint() { IsEmpty = true};
But knowing where the gaps are in advance is the challenge! The 'best' way is to go over the data and filling in the before adding the points. Or go over it later and instead of adding, inserting the dummys at the gaps. Both is a lot more trouble than getting the data right in the first place!
I have a datatable with steps history for a request.
Here is an example of the data:
I need to place on days how many days between each status has been passed.
Of course if there is only one status then the days should be the days elapsed between the transaction day and today's date.
Any clue?
This may help you to solve the issue:
Iterate through the collection, subtract the date column value of the previous row from current row .TotalDays() will returns you a double value indicates the day difference. this can be implemented as follows:
var temTable = myDatatable.AsEnumerable().Select(x => x).ToList();
for (int i = 0; i < temTable.Count; i++)
{
double days = 0;
if (i != 0)
days = ((DateTime)temTable[i]["date"] - (DateTime)temTable[i - 1]["date"]).TotalDays;
temTable[i]["days"] = days;
}
SELECT r.dDate,r.dHour,r.dStatus,DATEDIFF(
DAY,LAG(r.dDate,1,GETDATE())
OVER (ORDER BY r.dDate),r.dDate) AS DAYS
FROM tbData r;
I believe, above query in Sql Server will provide the desired output.
But to update the table with a new column "days" some additional/other code is required. I'm still working on it. And if you get the solution please post...
I didn't take time into my consideration...... You add that too....
You can use a field with type datetime (replace date and hour), will reduce the risk....
WITH newTable AS (
SELECT dStatus,ABS(DATEDIFF(
DAY,LAG(dDate,1,GETDATE())
OVER (ORDER BY dDate),dDate)) AS dDays FROM tbData
)
UPDATE tbData SET dDays=nt.dDays
FROM newTable nt
WHERE nt.dStatus = tbData.dStatus;
I believe this will resolve your problem.....
Hour field is not considered.....Thank You....
I am using sql server to store employee lunch in and out time and calculating difference using asp.net as below. Now i want to see if they exceed 30 mins then value should be in red color.
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Lunch Total Time
Label lunIn = (Label)e.Row.FindControl("lblLunIn");
Label lunOut = (Label)e.Row.FindControl("lblLunOut");
Label lunTotal = (Label)e.Row.FindControl("lblLunTotal");
lunTotal.Text = Convert.ToString(Convert.ToDateTime(lunOut.Text) - Convert.ToDateTime(lunIn.Text));
}
How should i go about it? Thanks
In general i would prefer to use the real data-source instead of the text in the GridViewRows. You can get it easily in RowDataBound via e.Row.DataItem. On that way you prevent localization issues and your work with the original data.
However, to get the time in minutes from two DateTimes you can subtract them and use the returned TimeSpans TotalMinutes property:
DateTime dtIn = Convert.ToDateTime(lunIn.Text);
DateTime dtOut = Convert.ToDateTime(lunOut.Text);
TimeSpan duration = dtOut - dtin;
lunTotal.Text = duration.ToString();
if(duration.TotalMinutes > 30)
{
e.Row.BackColor = Color.Red;
// or maybe you just want to change the color of the Label
lunTotal.ForeColor = Color.Red;
}
Okay so I have a datetime x-axis on an MSChart. I want to plot months below the first of each month and years below the change of a year. Here's what I have so far:
for (int i = 0; i < rdate.Length -1 ; i++)
{
if (rdate[i].Day == 01 && set == 0)
chart1.ChartAreas[0].AxisX.CustomLabels.Add(
rdate[i].AddDays(-20).ToOADate(), rdate[i].AddDays(20).ToOADate(),
Convert.ToString(rdate[i].ToString("MMMM")), 1, LabelMarkStyle.None);
set = 1;
if (rdate[i].Day > 01)
set = 0;
i++;
if (rdate[i].Year > rdate[i-1].Year)
chart1.ChartAreas[0].AxisX.CustomLabels.Add(
rdate[i].AddDays(-20).ToOADate(), rdate[i].AddDays(20).ToOADate(),
Convert.ToString(rdate[i].ToString("yyyy")), 2, LabelMarkStyle.None);
}
However for some reason this skips some months... The years do not show up at all.
rdate is a datetime array used to populate the x axis.
Here is an example of what my code does:
As you can see, the labels are behaving unexpectedly. I would also like to show a larger tick mark for these dates, and reduce the number of day labels based upon the date range, but I'm at a loss. Anyone done this sort of thing before?
I recently had a similar issue with MSChart when adding too many labels to the x-axis. The solution was reduce the number of ticks without losing data.
This approach worked for me but you will have to adapt it to your specific needs.
dataSeries.XValueType = ChartValueType.Auto;
dataSeries.Points.AddXY(record.DateTime, value);
I then determined the min and max dates for the given data to determine the preferred interval, your implementation will vary:
var totalDays = (maxDate.Value - minDate.Value).TotalDays;
if (totalDays < 60)
chartArea.AxisX.IntervalType = DateTimeIntervalType.Days;
else if (totalDays < 120)
chartArea.AxisX.IntervalType = DateTimeIntervalType.Weeks;
else
chartArea.AxisX.IntervalType = DateTimeIntervalType.Months;
Specify the AxisX label format:
In your case you might have to change the Format together with the interval.
chartArea.AxisX.LabelStyle.Format = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;
Hopefully there are some key parts that will provide value for you but you still have to modify it for your particular needs.