Convert.ToDateTime DD:HH:mm:ss C#/ASP.net GridView RowDataBound - c#

The basis of my question is to color a cell in a ASP.net Grid View control.
I have a bound field that is produced from this in SQL
RIGHT('0' + CONVERT(varchar(6), SUM([Coaching]) / 86400), 2) + ':' + RIGHT('0' + CONVERT(varchar(6), SUM([Coaching]) % 86400 / 3600), 2) + ':' + RIGHT('0' + CONVERT(varchar(2), SUM([Coaching]) % 3600 / 60), 2) + ':' + RIGHT('0' + CONVERT(varchar(2), SUM([Coaching]) % 60), 2)
It is not great for working with I know but the Project rules that I have says I have to have in a format of DD:HH:MM:SS for the display.
All that being said I'm trying to do a row data bound event in C# to color the cell if it is over a certain Minute
protected void TheGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
//this is where we will color the columns
if (e.Row.RowType == DataControlRowType.DataRow)
{
int CoachingIndex = GetColumnIndexByName(e.Row, "Coaching");
DateTime CoachingValue = Convert.ToDateTime(e.Row.Cells[CoachingIndex].Text);
string columnValue = ((Label)e.Row.FindControl("Coaching")).Text;
if (Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, columnValue)) > Convert.ToDateTime("00:00:40:00"))
{
e.Row.Cells[CoachingIndex].BackColor = System.Drawing.Color.Red;
}
}
}
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}
This conversion if (Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, columnValue)) > Convert.ToDateTime("00:00:40:00")) is where the problem lies just trying to figure out how to get this to work in C# so I can do the comparison.
Any help will be appreciated.

Thank you for all the help I was able to work on it today after all the info provided was able to get it to work.
if (e.Row.RowType == DataControlRowType.DataRow)
{
int CoachingIndex = GetColumnIndexByName(e.Row, "Coaching");
TimeSpan timeStamp;
string timeStampString = e.Row.Cells[CoachingIndex].Text; // just change the index of cells to get the correct timestamp field
if (TimeSpan.TryParse(timeStampString, out timeStamp))
{
TimeSpan TS = timeStamp;
int mins = TS.Minutes;
int hours = TS.Hours;
int days = TS.Days;
if (mins > 40 || hours >= 1 || days >= 1)
{
e.Row.Cells[CoachingIndex].BackColor = System.Drawing.Color.Red;
}
}
}
}
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}

Try using a common safe function like that while parsing the date:
public DateTime? GetSafeDateTimeValue(object datetimeValue)
{
if (datetimeValue == null || datetimeValue == DBNull.Value)
return null;
else
{
try
{
if (!DateTime.TryParse(datetimeValue.ToString(), out tempDateTimeValue))
return null;
else
return tempDateTimeValue;
}
catch
{
return null;
}
}
}
And replace your line with
DateTime? dt = GetSafeDateTimeValue((DataBinder.Eval(e.Row.DataItem, columnValue)));
if(dt.HasValue)
if (dt.Value > Convert.ToDateTime("00:00:40:00"))
Second problem you will face that the date time parser must expect the year, instead of parsing the datetime string take datetime instance like below:
DateTime comparedDt = new DateTime(2014, 03, 10, 00, 40, 00);

Related

maximum and minimum value in list

I'm currently doing my current project and I had a problem. Here's what the project needs to do:
Find the maximum and the minimum temperature from a certain range of date. The range of the date will be inputted by the user.
So, I make a form as the main menu for inputting the items and finding the maximum and minimum value (both in the new form). I also make a class to store the items:
public class TempDate
{
public double Temp { get; set; }
public DateTime Date { get; set; }
}
In the first form, just call it FormAddData, from here items will be stored into the list using a textbox and here's the code:
private void buttonSubmit_Click(object sender, EventArgs e)
{
FormMenu formMenu = (FormMenu)this.Owner;
DateTime date = dateTimePickerDate.Value.Date;
double temp = double.Parse(textBoxTemp.Text);
TempDate tempDate = new TempDate();
tempDate.Date = date;
tempDate.Temp = temp;
formMenu.listOfTempDate.Add(tempDate);
listBoxInfo.Items.Add(date + "\t" + temp + "°C");
}
In the second form that called FormMaxMinRange. In this form, I use two DateTimePicker the first one for the starting date and the second for the ending date. From here I need to make a button that will select all the items from the range that I used from starting and ending date. Here's my code:
private void buttonMaxMin_Click(object sender, EventArgs e)
{
FormMenu formMenu = (FormMenu)this.Owner;
DateTime start = dateTimePickerStart.Value.Date;
DateTime end = dateTimePickerEnd.Value.Date;
int highest = 0;
double max = formMenu.listOfTempDate[0].Temp;
int lowest = 0;
double min = formMenu.listOfTempDate[0].Temp;
for (int i = 1; i < formMenu.listOfTempDate.Count; i++)
{
if (formMenu.listOfTempDate[i].Date >= start
&& formMenu.listOfTempDate[i].Date <= end)
{
if (formMenu.listOfTempDate[i].Temp > max)
{
highest = i;
max = formMenu.listOfTempDate[i].Temp;
}
if (formMenu.listOfTempDate[i].Temp < min)
{
lowest = i;
min = formMenu.listOfTempDate[i].Temp;
}
}
}
listBoxMaxMin.Items.Add("");
listBoxMaxMin.Items.Add("Lowest temp: " + min + ", on " + formMenu.listOfTempDate[lowest].Date);
listBoxMaxMin.Items.Add("Highest temp: " + max + ", on " + formMenu.listOfTempDate[highest].Date);
}
Here's the main form that i declared the class (which include the list):
public partial class FormMenu : Form
{
public List<TempDate> listOfTempDate = new List<TempDate>();
public FormMenu()
{
InitializeComponent();
}
private void fromCertainRangeToolStripMenuItem_Click(object sender, EventArgs e)
{
FormMaxMinRange formMaxMinRange = new FormMaxMinRange();
formMaxMinRange.Owner = this;
formMaxMinRange.ShowDialog();
}
}
But, the problem is, the minimum value was not selected inside the range of selection. Also I want the max and min value was printed in the listbox. Sorry for the long and weird question. I hope someone can understand what I means with this question to complete my project. Thank you.
See this code snippet.
You can use Linq to select the reduced list (with Start/Enddate) and order it by Temp. Now you can easy select the first (min) and the last (max) object.
List<TempDate> loTempDateList = new List<TempDate>()
{
new TempDate() {Date = DateTime.Now.AddDays(-10), Temp = 10.01 },
new TempDate() {Date = DateTime.Now.AddDays(-5), Temp = 20.01 },
new TempDate() {Date = DateTime.Now.AddDays(-3), Temp = 30.01 },
new TempDate() {Date = DateTime.Now, Temp = 40.01 }
};
DateTime ldStart = DateTime.Now.AddDays(-6);
DateTime ldEnd = DateTime.Now.AddDays(-1);
var loDateList = loTempDateList.Where(item => item.Date <= ldEnd && item.Date >= ldStart)
.OrderBy(item => item.Temp);
TempDate loMin = loDateList.First();
TempDate loMax = loDateList.Last();
Console.WriteLine("{0}: {1} with max temp", loMax.Date, loMax.Temp);
Console.WriteLine("{0}: {1} with min temp", loMin.Date, loMin.Temp);
Output (for today):
9/26/2017 3:17:09 PM: 30.01 with max temp
9/24/2017 3:17:09 PM: 20.01 with min temp
Update (with your variable names):
Copy this under DateTime end = dateTimePickerEnd.Value.Date;in your Form
var loDateList = listOfTempDate.Where(item => item.Date <= end && item.Date >= start)
.OrderBy(item => item.Temp);
TempDate loMin = loDateList.FirstOrDefault();
TempDate loMax = loDateList.LastOrDefault();
if (loMin != null && loMax != null)
{
listBoxMaxMin.Items.Add("");
listBoxMaxMin.Items.Add("Lowest temp: " + loMin.Temp + ", on " + loMin.Date);
listBoxMaxMin.Items.Add("Highest temp: " + loMax.Temp + ", on " + loMax.Date);
}
I would suggest you use Linq Max and Min methods.
// filter out only the dates in the range you need
var items = formMenu.listOfTempDateWhere(
item => ((TempDate)item).Date >= start && ((TempDate)item).Date <= end
);
// get the maximum value
var max = items.Max(item => item.Temp);
// get the minimum value
var min = items.Min(item => item.Temp);
Just remember to add using System.Linq on the top of your .cs file
try this online
If you don't like a LINQ approach (I never use LINQ, for some, possibly invalid reason, I think it's evil), you can override the List class and extend it with methods of your own.
public class TempDataList<T> : List<TempData>
{
public TempDataList() : base()
{
}
public TempDataList(IEnumerable<TempData> collection) : base(collection)
{
}
public TempData GetMaxTemp(DateTime startDate, DateTime endDate)
{
TempData highestTempData = null;
for (int i = 0; i < this.Count; i++)
{
if (this[i].Date >= startDate && this[i].Date <= endDate)
{
if (highestTempData == null || this[i].Temp > highestTempData.Temp)
{
highestTempData = this[i];
}
}
}
return highestTempData;
}
public TempData GetMinTemp(DateTime startDate, DateTime endDate)
{
TempData lowestTempData = null;
for (int i = 0; i < this.Count; i++)
{
if (this[i].Date >= startDate && this[i].Date <= endDate)
{
if (lowestTempData == null || this[i].Temp < lowestTempData.Temp)
{
lowestTempData = this[i];
}
}
}
return lowestTempData;
}
}
And fill the extended list and call the methods:
TempDataList<TempData> tempDataList = new TempDataList<TempData>();
tempDataList.Add(new TempData(10, DateTime.UtcNow));
tempDataList.Add(new TempData(20, DateTime.UtcNow));
tempDataList.Add(new TempData(15, DateTime.MinValue));
tempDataList.Add(new TempData(25, DateTime.MaxValue));
Console.WriteLine(tempDataList.GetMaxTemp(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1)).Temp);
Console.WriteLine(tempDataList.GetMinTemp(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1)).Temp);

Calculating time difference in C# and saving to mysql

I've been assigned with the task of calculating a time difference only counting working hours. After searching I was able to get this (it's kinda in Portuguese but I think it's understandable) :
if (!txt_data2.Text.Contains("_") && !string.IsNullOrEmpty(txt_data2.Text) && txt_data2.Text != null && !txt_hora2.Text.Contains("_") && !string.IsNullOrEmpty(txt_hora2.Text) && txt_hora2.Text != null)
{
TimeSpan hi = TimeSpan.Parse(txt_horainicio.Text);
TimeSpan hf = TimeSpan.Parse(txt_hora2.Text);
if (hi.Hours < 9 || hf.Hours > 18)
{
MessageBox.Show("Horas Inválidas");
}
else
{
if (MessageBox.Show("Inserir horas extraordinárias?", "Horas Extraordinárias", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
double extra;
TimeSpan horasextra;
Frm_Tempo frm1 = new Frm_Tempo();
if (frm1.ShowDialog() == DialogResult.OK)
{
horasextra = TimeSpan.Parse(frm1.txt_horasextra.Text);
extra = horasextra.TotalHours;
DateTime data1 = Convert.ToDateTime(txt_datainicio.Text);
TimeSpan hora1 = TimeSpan.Parse(txt_horainicio.Text);
DateTime dataentrega1 = Convert.ToDateTime(txt_data2.Text);
TimeSpan horaentrega1 = TimeSpan.Parse(txt_hora2.Text);
data1 = data1.Add(hora1);
dataentrega1 = dataentrega1.Add(horaentrega1);
double horas1 = 0;
double minutos1 = 0;
for (var i = data1; i < dataentrega1; i = i.AddMinutes(1))
{
if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
{
if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours <= 18)
{
if (i.TimeOfDay.Hours >= 13 && i.TimeOfDay.Hours < 14)
{
}
else
{
minutos1++;
for (var x = data1; x < dataentrega1; x = x.AddHours(1))
{
horas1 = (minutos1 / 60) + extra;
}
}
}
}
}
TimeSpan tempo1 = TimeSpan.FromHours(horas1);
MySqlCommand UPDATE20 = new MySqlCommand("UPDATE tbl_orcamentos SET tempo ='" + tempo1 + "'WHERE id ='" + txt_cod.Text + "'", ligar);
UPDATE20.ExecuteNonQuery();
}
}
else
{
DateTime data = Convert.ToDateTime(txt_datainicio.Text);
TimeSpan hora = TimeSpan.Parse(txt_horainicio.Text);
DateTime dataentrega = Convert.ToDateTime(txt_data2.Text);
TimeSpan horaentrega = TimeSpan.Parse(txt_hora2.Text);
data = data.Add(hora);
dataentrega = dataentrega.Add(horaentrega);
float horas = 0;
float minutos = 0;
for (var i = data; i < dataentrega; i = i.AddMinutes(1))
{
if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
{
if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 18)
{
if (i.TimeOfDay.Hours >= 13 && i.TimeOfDay.Hours < 14)
{
}
else
{
minutos++;
for (var x = data; x < dataentrega; x = x.AddHours(1))
{
horas = minutos / 60;
}
}
}
}
}
TimeSpan tempo = TimeSpan.FromHours(horas);
MySqlCommand UPDATE21 = new MySqlCommand("UPDATE tbl_orcamentos SET tempo ='" + tempo + "'WHERE id ='" + txt_cod.Text + "'", ligar);
UPDATE21.ExecuteNonQuery();
}
}
}
I'm using c# and a mysql database.
It seems to work but when the result was 48h, instead of "48:00:00", it's trying to update it to "2.00:00:00" which isn't valid as "tempo" it's a time field in mysql. I don't really know how to solve it and so far I've tried to make "horas" a datetime and then formatting it to the right format but it didn't work.
I'd really appreciate any help and I'm sorry if it's hard to understand, just ask and I'll try to explain further.
EDIT:
Adding the float "horas" which contains the number of hours into the Timespan:
TimeSpan tempo = TimeSpan.FromHours(horas);
The standard SQL data type for a difference in time is "interval". MySQL doesn't support the "interval" data type.
It can be confusing, because times of day and intervals use the same notation, but have different meanings. The value '1:00' means 1 o'clock if it's a time of day ("time" or "timestamp"). But the same value means one hour if it's an interval.
Also, "48:00:00" is a valid interval (48 hours), but it's not a valid time of day.
If you're using MySQL, calculate and store the interval in an integer representing the number of hours, minutes, or seconds, and format for display. For example, store two hours as the integer 7200 (seconds) or as the integer 120 (minutes), depending on the application's requirements. Format that integer as "2:00" for display. C#'s TimeSpan.FromMinutes and TimeSpan.FromSeconds will help.
If you want to play around with an open source dbms that supports intervals, look at PostgreSQL.

How can I paint selected rows in a DataGridView based on the values in two of the cells?

I am populating a DataGridView with a semicolon-delimited text file like so:
private void ExistingAppntmntRecs_Load(object sender, EventArgs e)
{
DataTable dt = SeparatedValsFileToDataTable(APPOINTMENTS_FILE_NAME, ";");
dataGridViewExistingAppntmntRecs.DataSource = dt;
}
// from http://stackoverflow.com/questions/39434405/read-csv-to-datatable-and-fill-a-datagridview (Frank)
public static DataTable SeparatedValsFileToDataTable(string filename, string separatorChar)
{
var table = new DataTable("Filecsv");
using (var sr = new StreamReader(filename, Encoding.Default))
{
string line;
var i = 0;
while (sr.Peek() >= 0)
{
try
{
line = sr.ReadLine();
if (string.IsNullOrEmpty(line)) continue;
var values = line.Split(new[] { separatorChar }, StringSplitOptions.None);
var row = table.NewRow();
for (var colNum = 0; colNum < values.Length; colNum++)
{
var value = values[colNum];
if (i == 0)
{
table.Columns.Add(value, typeof(String));
}
else
{ row[table.Columns[colNum]] = value; }
}
if (i != 0) table.Rows.Add(row);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
i++;
}
}
return table;
}
What I want to do now is to color the rows which have an EndDate value within two months of the current date yellow, within one month orange, and those with a date in the past (meaning they have lapsed) red.
There is a PostPaint event which may work, but I don't know how to examine cell contents within the row in that event handler:
private void dataGridViewExistingAppntmntRecs_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
// What now?
}
Here is the contents of the file that is read (bogus/test data, with a header row prepended):
person;phone;email;org;addr1;addr2;city;st8;zip;visitNum;success;adSizeLoc;meetingLoc;meetingDate;meetingTime;adBeginMonth;adBeginYear;adEndMonth;adEndYear;Notes
B.B. King;2221113333;bbking#blues.com;Virtuosos;1234 Wayback Lane;;Chicago;IL;98765;1;false;Full Page Inside Front Cover;Same as Org Address;4/5/2017 2:03:12 PM;9:00 am;May;2017;May;2018;Lucille was her name
Linda Ronstadt;55577889999;rhondalinstadt#eaglet.com;Eagles Singer;La Canada;;Los Angeles;CA;99988;1;false;Full page Inside Back Cover;Same as Org Address;4/5/2017 2:05:23 PM;9:00 am;May;2017;May;2018;She had some good stuff
If the adEndMonth + adEndYear date equates to 2 months or less away, the entire row should be yellow; if 1 month or less away, orange; if today or in the past, paint it red. Finally, if one of the Rolling Stones is running the app, paint it black.
Here is some pseudocode for the PostPaint event, with "TODO:" where I don't know what to do:
private void dataGridViewExistingAppntmntRecs_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DateTime twoMonthsLimit = DateTime.Now.AddMonths(2);
DateTime oneMonthLimit = DateTime.Now.AddMonths(1);
int endYear = // TODO: assign adEndYear value
int endMonth = // TODO: assign adEndMonth value
DateTime endDate = new DateTime(endYear, endMonth, 1);
if (twoMonthsLimit > endDate) // TODO: paint row yellow
if (oneMonthLimit > endDate) // TODO: paint row orange
if (endDate < DateTime.Now) // TODO: paint row red
}
If the goal is too simply, highlight the rows that fall within certain dates, then changing the rows background color may be an easier option. Repainting the rows may be unnecessary. My solution simply changes the rows background color depending on the dates in the “endMonth” and “endYear” columns.
The cell formatting is an option however, it will fire often and placing this “Coloring” checks every time a cell is changed or displayed is unnecessary. If the rows have already been “Colored”, then the only things to look for is when new rows are added or the values in the “endMonth” or “endYear” columns are changed.
Below is code that simply loops through the DataGridView and sets each row color based on the criteria you described. The logic to get a rows color is fairly straightforward (minus the paint it black). If the date is greater than two months forward from today’s date then leave the background color white. If the date is greater than 1 month but less than 2 months then color the row yellow… etc.
I used a similar approach to read the text file and create the DataTable. Hope this helps.
DataTable dt;
string filePath = #"D:\Test\Artist.txt";
char delimiter = ';';
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
dt = GetTableFromFile(filePath, delimiter);
dataGridViewExistingAppntmntRecs.DataSource = dt;
UpdateDataGridColors();
}
private DataTable GetTableFromFile(string filePath, char delimiter) {
List<string[]> allArtists = GetArtistList(filePath, delimiter);
DataTable dt = GetTableColumns(allArtists[0]);
int totalCols = dt.Columns.Count;
DataRow dr;
for (int i = 1; i < allArtists.Count; i++) {
string[] curArtist = allArtists[i];
dr = dt.NewRow();
for (int j = 0; j < totalCols; j++) {
dr[j] = curArtist[j].ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
private List<string[]> GetArtistList(string inFilePath, char inDelimiter) {
string pathToFile = inFilePath;
char delimiter = inDelimiter;
List<string[]> listStringArrays = File.ReadAllLines(pathToFile).Select(x => x.Split(delimiter)).ToList();
return listStringArrays;
}
private DataTable GetTableColumns(string[] allHeaders) {
DataTable dt = new DataTable();
foreach (string curHeader in allHeaders) {
dt.Columns.Add(curHeader, typeof(string));
}
return dt;
}
private Color GetColorForRow(DataRowView dr) {
// paint it black ;-)
if (dr[0].ToString().Equals("Rolling Stones")) {
return Color.Black;
}
DateTime rowDate;
DateTime dateNow = DateTime.Now;
DateTime twoMonthsLimit = dateNow.AddMonths(2);
DateTime oneMonthLimit = dateNow.AddMonths(1);
if (dr != null) {
string rowStringMonth = dr[17].ToString();
string rowStringYear = dr[18].ToString();
string rowStringDate = "1/" + rowStringMonth + "/" + rowStringYear;
if (DateTime.TryParse(rowStringDate, out rowDate)) {
if (rowDate > twoMonthsLimit)
return Color.White;
if (rowDate > oneMonthLimit)
return Color.Yellow;
if (rowDate > dateNow)
return Color.Orange;
if (rowDate.Month == dateNow.Month && rowDate.Year == dateNow.Year)
return Color.Orange;
// this row date is less than todays month date
return Color.Red;
} // else date time parse unsuccessful - ignoring
}
// date is null
return Color.White;
}
private void UpdateDataGridColors() {
Color rowColor;
DataRowView dr;
foreach (DataGridViewRow dgvr in dataGridViewExistingAppntmntRecs.Rows) {
dr = dgvr.DataBoundItem as DataRowView;
if (dr != null) {
rowColor = GetColorForRow(dr);
dgvr.DefaultCellStyle.BackColor = rowColor;
if (rowColor == Color.Black)
dgvr.DefaultCellStyle.ForeColor = Color.White;
}
}
}
private void dataGridViewExistingAppntmntRecs_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
if (e.ColumnIndex == 17 || e.ColumnIndex == 18) {
//MessageBox.Show("End Date Changed");
UpdateDataGridColors();
}
}
private void dataGridViewExistingAppntmntRecs_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
UpdateDataGridColors();
}

DateTime Custom Formatting for Seasons

I've come across a problem customizing my DateTimePicker value in my application. I've read all about the various formatting strings which you can use to customize the way the date/time is interpreted. The issue is that I actually want some of the text to be ignored in the custom format string so that I can add in the season as a string to the beginning of the DateTimePicker.
For example, let's take today's date which is August 7th, 2013 at 5:30PM (in the US). If I use the custom format string "MMM.d -h:mm tt" then the date will be shown as Aug. 7th - 5:30PM. So, that's perfect. Only, I want to add the season to the beginning of the string. So, in this case, it would be "Summer: Aug. 7th - 5:30PM".
The issue that I'm having is that if I insert the word "Summer" at the beginning of the custom format string, then it actually interprets the double mm's as GetMinute value of the dateTime. I'd like for the season to remain literal, but the rest of the format string to be interpreted (if that makes sense).
Here is the code I'm using:
public Form1()
{
InitializeComponent();
dateTimePicker1.Format = DateTimePickerFormat.Custom;
season = getSeason(dateTimePicker1.Value);
dateTimePicker1.CustomFormat = convertSeason(season) + " : " + dt_format;
}
public int season = 1; //set default to summer
public string dt_format = "MMM.d -h:mm tt";
private int getSeason(DateTime date)
{
float value = (float)date.Month + date.Day / 100; // <month>.<day(2 digit)>
if (value < 3.21 || value >= 12.22) return 3; // Winter
if (value < 6.21) return 0; // Spring
if (value < 9.23) return 1; // Summer
return 2; // Autumn
}
private string convertSeason(int value)
{
string season = "Spring";
if (value == 1) season = "Summer";
else if (value == 2) season = "Autumn";
else if (value == 3) season = "Winter";
return season;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
season = getSeason(dateTimePicker1.Value);
dateTimePicker1.CustomFormat = convertSeason(season) + " : " + dt_format;
}
You need to surround it in a literal string delimiter (for DateTime format strings): '.
So now your method could be this:
private string convertSeason(int value)
{
string season = "'Spring'";
if (value == 1) season = "'Summer'";
else if (value == 2) season = "'Autumn'";
else if (value == 3) season = "'Winter'";
return season;
}
However, your methods could be improved a bit. So I took the liberty of doing that:
private int GetSeason(DateTime date)
{
//using decimal to avoid any inaccuracy issues
decimal value = date.Month + date.Day / 100M; // <month>.<day(2 digit)>
if (value < 3.21 || value >= 12.22) return 3; // Winter
if (value < 6.21) return 0; // Spring
if (value < 9.23) return 1; // Summer
return 2; // Autumn
}
private string ConvertSeason(int value)
{
switch (value)
{
case 0:
return "'Spring'";
case 1:
return "'Summer'";
case 2:
return "'Autumn'";
case 3:
return "'Winter'";
}
return "";
}

c# error: Input string not in correct format

I have a datagrid view which is editable. I'm getting the value of a cell and then calculate the value of another cell. To do this I have handled CellEndEdit and CellBeginEdit events.
quantity = 0, quantity1 = 0, quantity_wt1 = 0, quantity_wt = 0, ekundag = 0;
private void grdCaret_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
quantity = val;
ekundag = ekundag + quantity;
tbTotDag_cr.Text = ekundag.ToString();
}
if (e.ColumnIndex == 2)
{
float val = float.Parse(value);
total = val;
ekunrakam = ekunrakam + total;
tbTotPrice_cr.Text = ekunrakam.ToString();
}
grdCaret.Columns[3].ReadOnly = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void grdCaret_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
rate = 0;
quantity1 = quantity;
total1 = total;
rate = (total1 / quantity1);
if (e.ColumnIndex == 3)
{
grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = rate.ToString();
grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = true;
// quantity = 0;
// total = 0;
}
}
In the grid I have columns as quantity, total and rate. I get the above error here:
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
quantity = val;
ekundag = ekundag + quantity;
tbTotDag_cr.Text = ekundag.ToString();
}
When I enter quantity and click on the total column in gridview. Please help me fix this
AFAIK the int.Parse() function can possibly cause this kind of exceptions.
Have you tried to check the value in the cell? Isn't it possible, that some other characters are in the cell, not only the numbers? White spaces for example.
The value you have entered into your Cell can't be parsed as Integer, so it will fail #
int val = int.Parse(value);
Your input string 'value' is not in a valid format to be parsed to an integer. Take a look at this: http://www.codeproject.com/Articles/32885/Difference-Between-Int32-Parse-Convert-ToInt32-and
try using Text instead of ToString()
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.Text;
in place of
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

Categories

Resources