hye, i'm having a problem when i'm inserting data in textbox.the problem is when i'm searching for data 10/10/2010, it work perfectly but when i try to search other date (eg 25/11/2013), i would get error The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. the error occur at "gridmaxdata.DataBind();"
protected void searchdata_Click(object sender, EventArgs e)
{
data();
byday2();
}
public void data()
{
if (Dayrange.Checked == true)
{
startdate = DateTime.ParseExact(txtStart1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
enddate = DateTime.ParseExact(txtEnd1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
//starttime = DateTime.ParseExact(txtStart1.Text, "HH:mm:ss", CultureInfo.InvariantCulture);
//endtime = DateTime.ParseExact(txtStart1.Text, "HH:mm:ss", CultureInfo.InvariantCulture);
Label1.Text = startdate.ToShortDateString();
Label2.Text = enddate.ToShortDateString();
}
if (Byday.Checked == true)
{
startdate = DateTime.ParseExact(txtStart1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
enddate = startdate.AddDays(1);
//starttime = DateTime.ParseExact(txtStart1.Text, "HH:mm:ss", CultureInfo.InvariantCulture);
//endtime = DateTime.ParseExact(txtStart1.Text, "HH:mm:ss", CultureInfo.InvariantCulture);
Label1.Text = startdate.ToShortDateString();
Label2.Text = enddate.ToShortDateString();
}
}
public void byday2()
{
if (Byday.Checked == true)
{
if (Maxdata.Checked == true)
{
//tablemax.hidden = true;
lblmaxdata.Visible = true;
lblmaxdata.Text = "Highest Data";
// ConnectionString to NorthWind Database.
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\shafiq\\Desktop\\history\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True";
// Create SQLDataSource.
SqlDataSource sqlDataSource = new SqlDataSource();
sqlDataSource.ID = "SqlDataSource123";
this.Page.Controls.Add(sqlDataSource);
// Bind ConnectionString to SQLDataSource.
sqlDataSource.ConnectionString = connectionString;
// Retrieve records with only 5 Columns from Employees table of NorthWind Database.
sqlDataSource.SelectCommand = "SELECT [date], [data] FROM [loc1] WHERE (([data] >= '2') AND ([date] >= '" + Convert.ToDateTime(startdate).ToString("dd/MM/yyyy") + "') AND ([date] < '" + Convert.ToDateTime(enddate).ToString("dd/MM/yyyy") + "')) ORDER BY [data] DESC, [date] DESC";
// Bind SQLDataSource to GridView after retrieving the records.
gridmaxdata.DataSource = sqlDataSource;
gridmaxdata.DataBind();
}
}
}
better to use parameters
sqlDataSource.SelectCommand = "SELECT [date], [data] FROM [loc1] WHERE (([data] >= '2') AND ([date] >= #startdate) AND ([date] < #enddate)) ORDER BY [data] DESC, [date] DESC";
sqlDataSource.SelectCommand.Parameters.AddwithValue("#startdate",startdate);
sqlDataSource.SelectCommand.Parameters.AddwithValue("#enddate",enddate);
it is because in the date 25/11/2013, 25 gets as month, 11 gets as date and 2013 gets as year. hence there is no month 25. then it will throw an exception.
you can try this approach convert(varchar, startdate, 103)
for more information http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/
Related
i have a form which collects 2 dates (start date & end date) in the format mm/dd/yyyy
I want to collect these 2 dates from the form, and then create a list of all dates between these 2 days, then insert them into seperate rows in mt database. Here is my code:
if(IsPost){
var bookedFrom = Request.Form["dateFrom"];
var bookedTo = Request.Form["dateTo"];
DateTime dateF = Convert.ToDateTime(bookedFrom);
DateTime dateT = Convert.ToDateTime(bookedTo);
var dates = new List<DateTime>();
for (var dt = dateF; dt <= dateT; dt = dt.AddDays(1))
{
dates.Add(dt);
}
foreach(var dat in dates){
db.Execute("INSERT INTO Property_Availability (PropertyID, BookedDate, BookedNotes, BookedType) VALUES (#0, #1, #2, #3)", rPropertyId, dat, Request.Form["BookedNotes"], Request.Form["BookedType"]);
}
}
However, when i try and post my form, i get the following error:
String was not recognized as a valid DateTime.
DateTime dateF = Convert.ToDateTime(bookedFrom);
Any idea where i'm going wrong?
Thanks
Just my 2 cents in help you out, also consider using debug to know whether what values are passed / etc.
if(IsPost){
DateTime pFrom = new DateTime();
DateTime pTo = new DateTime();
var bookedFrom = Request.Form["dateFrom"];
var bookedTo = Request.Form["dateTo"];
if(DateTime.TryParse(bookedFrom, out pFrom) && DateTime.TryParse(bookedTo, out pTo))
{
DateTime dateF = pFrom;
DateTime dateT = pTo;
var dates = new List<DateTime>();
for (var dt = dateF; dt <= dateT; dt = dt.AddDays(1))
{
dates.Add(dt);
}
foreach(var dat in dates){
db.Execute("INSERT INTO Property_Availability (PropertyID, BookedDate, BookedNotes, BookedType) VALUES (#0, #1, #2, #3)", rPropertyId, dat, Request.Form["BookedNotes"], Request.Form["BookedType"]);
}
}
else
{
Response.Write("<script language=javascript>alert('Invalid date from : " + bookedFrom + " and date to : " + bookedTo + "');</script>");
}
}
Based on your exception, you have some problems with format of Request.Form["dateFrom"] value.
For example date in your default locale is supposed to be in format 'dd/mm/yyyy' or something like that.
So if you exactly know format of date in this parameter it's better to use something like that
DateTime dateF = DateTime.ParseExact(bookedFrom, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here is my code
public void onStart()
{
cmd = new OleDbCommand(#"SELECT COUNT(*) FROM _Annual_Rate", mydb);
int counter = (int)cmd.ExecuteScalar();
adapter = new OleDbDataAdapter(#"SELECT * FROM _Annual_Rate ", mydb);
dt.Clear(); // Data Table = dt
adapter.Fill(dt);
DateTime[] date = new DateTime[counter];
for (int i = 0; i < counter; i++)
{
date[i] = Convert.ToDateTime(dt.Rows[i]["Date_Of_Rate"]);
}
dateTimePicker1.MinDate = date.Min();
dateTimePicker2.MinDate = dateTimePicker1.Value;
dateTimePicker1.MaxDate = dateTimePicker2.Value;
dateTimePicker2.MaxDate = date.Max();
dateTimePicker1.Value = dateTimePicker1.MinDate;
dateTimePicker2.Value = dateTimePicker2.MaxDate;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if (dateTimePicker1.Value >= dateTimePicker2.Value)
{
dateTimePicker1.Value = dateTimePicker1.MinDate;
}
else
{
dateTimePicker2.MinDate = dateTimePicker1.Value;
DateTime minDate = dateTimePicker1.Value;
DateTime maxDate = dateTimePicker2.Value;
adapter = new OleDbDataAdapter("SELECT * FROM _Annual_Rate WHERE Date_Of_Rate BETWEEN #" + minDate + "# AND #" + maxDate + "#", mydb);
dt.Clear();
adapter.Fill(dt);
MessageBox.Show("minDate:" + minDate + "\nmaxDate:" + maxDate);
}
}
Here is the results
Here is my MS Access Database
I have coded dateTimePicker2 precisely the same as dateTimePicker1 with some minor changes to pass errors like if (dateTimePicker2.Value <= dateTimePicker1.Value). Data disappear and reappear as I move through the calender that should not show or be gone. I can move dateTimePicker2 to the date 12/30/30 and then some dates will be gone where they should show or I move the date on dateTimePicker2 to 12/30/98 then the dates above it shows up. I can't find my error hopefully you can. The same with dateTimePicker1
I would remove the BETWEEN and the string concatenation.
Instead I would use a parameterized query like this
DateTime minDate = dateTimePicker1.Value;
DateTime maxDate = dateTimePicker2.Value;
string cmdText = #"SELECT * FROM _Annual_Rate
WHERE Date_Of_Rate >= ? AND Date_Of_Rage <= ?";
adapter = new OleDbDataAdapter(cmdText, mydb);
adapter.SelectCommand.Parameters.Add("#d1", OleDbType.Date).Value = minDate;
adapter.SelectCommand.Parameters.Add("#d2", OleDbType.Date).Value = maxDate;
dt.Clear();
adapter.Fill(dt);
In this way the database engine will see the minDate and maxDate exactly as dates and not as some kind of string interpretation of a date value.
(There is also the added benefit to prevent Sql Injection albeit in MS-Access is more difficult to exploit)
C#/MySQL - Set WinForm Access Date MySQL
So I created a MySQL Database which my form is able to access & login to. My goal for it is to be able to pull information from the MySQL Database into the form as a label (I know easy right?).
Example:
The hardest problem for me was figuring out how to store lets say a "Subscription" start/end date and be able to tell me on a label, how many days I had left on my subscription. All this using information for the database.
(Yes this database is for test purposes only no where near final.)
Created a table called edata.
Created fields the program would use
(Account Status/StartSub/EndSub)
My Question: How would I go about taking the dates entered and creating a value that I could use to show in the "Days Left Here" label?
I will create the table like this:
CREATE TABLE `test`.`New Table` (
`ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(45),
`LastName` VARCHAR(45),
`Username` VARCHAR(45),
`Password` VARCHAR(45),
`Account` INTEGER UNSIGNED,
`StartSub` DATETIME,
`EndSub` DATETIME,
PRIMARY KEY (`ID`)
)
ENGINE = InnoDB;
Then query like this:
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "select * from edata where id = 1;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
DateTime dateStart = Convert.ToDateTime(dt.Rows[0]["StartSub"]);
DateTime dateEnd = Convert.ToDateTime(dt.Rows[0]["EndSub"]);
if (DateTime.Now >= dateStart && DateTime.Now <= dateEnd)
{
TimeSpan ts = dateEnd - DateTime.Now;
label1.Text = "Active";
label2.Text = ts.TotalDays + " day(s) left";
}
else
{
label1.Text = "Expired";
label2.Text = "0 day left";
}
}
}
If you can parse the values out it is pretty simple, for example:
string end_date_string = "2014-09-24";
string start_date_string = "2014-09-18";
DateTime end_date = DateTime.Parse(end_date_string); // parse end date
DateTime start_date = DateTime.Parse(start_date_string); // parse start date
TimeSpan dur = end_date.Subtract(start_date); // total duration
TimeSpan timeleft = end_date.Subtract(DateTime.Now); // how much time left until we hit the end_date
Label l;
l.Text = timeleft.Days.ToString();
// l.Text = timeLeft.Hours.ToString();
// l.Text = timeleft.Minutes.ToString();
I need some assistance regarding to how to auto update StartDate and EndDate for next execution. At this moment, I manually add the StartDate and EndDate in sql database and if I didn’t change the StartDate and EndDate, my report will be generating using same StartDate and EndDate. Appreciate if you all can give any idea or suggestion about that. Thanks.
static void Main(string[] args)
{
DateTime start = System.DateTime.Now.AddMinutes(1);
Schedule.PeriodicSchedules schedule =
new Schedule.PeriodicSchedules(start,
Schedule.PeriodicSchedules.Frequency.Minutely);
schedule.Elapsed += new System.Timers.ElapsedEventHandler(GenerateReport);
schedule.Enabled = true;
Console.ReadLine();
}
static void GenerateReport(object sender, EventArgs e)
{
if (TypeOfReport == "BillingReport")
{
DateOfExecution = DateTime.Parse(strDOE);
Schedule.PeriodicSchedules s =
new Schedule.PeriodicSchedules(DateOfExecution,
Schedule.PeriodicSchedules.Frequency.Weekly);
crRpt.Load(BillingReport);
ReportLogin(crRpt);
while (ThisReader.Read())
{
//StartDate and EndDate >>next execution?
crRpt.SetParameterValue("#CollectionStartDate", StartDate);
crRpt.SetParameterValue("#CollectionEndDate", EndDate);
crRpt.SetParameterValue("#SpokeCode", SpokeCode);
}
}
if (TypeOfReport == "ImageReport")
{
DateOfExecution = DateTime.Parse(strDOE);
Schedule.PeriodicSchedules s =
new Schedule.PeriodicSchedules(DateOfExecution,
Schedule.PeriodicSchedules.Frequency.Monthly);
crRpt.Load(ImageReport);
ReportLogin(crRpt);
crRpt.SetParameterValue("#CollectionStartDate", StartDate);
crRpt.SetParameterValue("#CollectionEndDate", EndDate);
crRpt.SetParameterValue("#SpokeCode", SpokeCode);
}
}
I manage to do it by call another method to auto update my DateOfExecution. Let me know if someone have another way. :)
static void GenerateReport(object sender, EventArgs e)
{
if (TypeOfReport == "BillingReport")
{
......
DateOfExecution = DateTime.Parse(strDOE);
Schedule.PeriodicSchedules s = new Schedule.PeriodicSchedules(DateOfExecution, Schedule.PeriodicSchedules.Frequency.Minutely);
//weekly
DateTime StartDate = DateOfExecution.AddDays(-7);
DateTime EndDate = DateOfExecution.AddDays(-1);
..........
UpdateWeekly(DateOfExecution, strReportType);
}
}
static void UpdateWeekly(DateTime DateOfExecution, String strReportType)
{
DateOfExecution = DateOfExecution.AddMinutes(2);
SqlConnection thisConnection = new SqlConnection(SQLConnection);
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
//thisCommand.CommandText = "INSERT INTO dbo.Schedules (DateOfExecution)" + "Values('"+DateOfExecution+"')";
thisCommand.CommandText = "UPDATE dbo.Schedule set DateOfExecution = '" + DateOfExecution + "' WHERE TypeOfReport = '" + strReportType + "'";
thisCommand.ExecuteNonQuery();
}
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