I have a database date "2014-11-26". I have a calender with format(dd-MM-yyyy) I am trying to bring some values to my form from databse by textbox selected date
protected void txtdate_TextChanged(object sender, EventArgs e)
{
//DateTime timeIn = Convert.ToDateTime(txtdate.Text);
// DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
str = "select TimeIn,TimeOut from MusterRoll where EmpCode='" + ddcode.SelectedItem.Text + "' and Date='"+time1+"'";
dr = conn.query(str);
if (dr.Read())
{
DateTime time = dr.GetDateTime(0);
TimeSelector1.SetTime(time.Hour, time.Minute, TimeSelector1.AmPm);
DateTime time2 = dr.GetDateTime(1);
TimeSelector2.SetTime(time2.Hour, time2.Minute, TimeSelector2.AmPm);
}
}
The problem is databse date format and my calender format is different. I tried two methods(which I placed in command line)but shows error message like "input string was not in correct format"
. I surfed internet and find these same answers. May I know why it shows error?? i am trying to make database dateformat and calender format as same
Best Solution
First of all, a
DateTime
doesn't have any implicit format. It has just date and time values.String
representations of them can have a format.I strongly suspect you save your
DateTime
values with their string representations which is a horrible idea. Read: Bad habits to kick : choosing the wrong data type Pass yourDateTime
values directly to your parameterized queries instead of their string representations. Anyway..For;
Convert.ToDateTime(string)
method usesDateTime.Parse
method with yourCurrentCulture
settings. That means if your string isn't a standard date and time format of yourCurrentCulture
your code throwsFormatException
. I guessdd-MM-yyyy
is not a standard date and time format of yourCurrentCulture
.For;
When you use
DateTime.ParseExact
, your string and format should match exactly.In your case; they are not (
"26-11-2014"
and"yyyy-MM-dd"
). Usedd-MM-yyyy
format instead.Then you can generate the format from your
time1
like;For your command part, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.