How to auto update startDate and EndDate for next execution? - c#

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();
}

Related

Populating Mysql Data to asp calendar takes too long to load

I'm creating a leave calendar for employees, And for that I'm populating some data onto the calendar using dataset, but it takes too long to load the data.
I'm using multiple MySqlDataReader and connections to read the data from MySql table for each row of the calendar table. Maybe using multiple connections and readers might be the cause of slowing down but I'm not sure. The below is the code I use to populate the data.
class Sample
{
public DateTime Date { get; set; }
public string SlotAvailable { get; set; }
public string Pending { get; set; }
public string HeadCount { get; set; }
}
DateTime firstDate { get; set; }
DateTime lastDate { get; set; }
List<Sample> samples = new List<Sample>();
protected DataSet dsleaveplanner;
protected void FillLeaveplannerDataset()
{
cal2.VisibleDate = cal2.TodaysDate;
DateTime firstDate = new DateTime(cal2.VisibleDate.Year, cal2.VisibleDate.Month, 1).AddDays(-6);
DateTime lastDate = new DateTime(cal2.VisibleDate.Date.AddMonths(1).Year, cal2.VisibleDate.Date.AddMonths(1).Month, 1).AddDays(7);
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (cal2.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = cal2.VisibleDate.Year + 1;
}
else
{
monthNumber = cal2.VisibleDate.Month + 1;
yearNumber = cal2.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
string site = lblsite.Text;
string skill = lblskill.Text;
string shift = lblshift.Text;
DataSet dsMonth = new DataSet();
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(MyConString);
string caldate = "Select * From setshrinkage Where date >= #firstDate And date <= #lastDate And site=#site And skill=#skill And shift=#shift Group By date";
MySqlCommand cmd = new MySqlCommand(caldate, con);
cmd.Parameters.AddWithValue("#firstDate", firstDate);
cmd.Parameters.AddWithValue("#lastDate", lastDate);
cmd.Parameters.AddWithValue("#site", site);
cmd.Parameters.AddWithValue("#skill", skill);
cmd.Parameters.AddWithValue("#shift", shift);
MySqlDataAdapter mysqlDataAdapter = new MySqlDataAdapter(cmd);
try
{
mysqlDataAdapter.Fill(dsMonth);
con.Close();
}
catch { }
return dsMonth;
}
public void caldisp(DayRenderEventArgs e)
{
Environment.NewLine.ToString();
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p></p>Slot available:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().SlotAvailable.ToString()));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().Pending.ToString()));
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
//e.Day.IsSelectable = false;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
var hcount = (dr["headCount"].ToString());
Int32 hcount1 = Convert.ToInt32(hcount);
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection conn = new MySqlConnection(MyConString);
string cntdate = "SELECT COUNT(date) FROM approved WHERE date = #date And site=#site And skill=#skill And shift=#shift And status=#status";
string cntdate2 = "SELECT COUNT(date) FROM approved WHERE date = #date And site=#site And skill=#skill And shift=#shift And status=#status";
MySqlCommand cmd2 = new MySqlCommand(cntdate, conn);
MySqlCommand cmd3 = new MySqlCommand(cntdate2, conn);
cmd2.Parameters.AddWithValue("#date", nextDate);
cmd2.Parameters.AddWithValue("#site", lblsite.Text);
cmd2.Parameters.AddWithValue("#skill", lblskill.Text);
cmd2.Parameters.AddWithValue("#shift", lblshift.Text);
cmd2.Parameters.AddWithValue("#status", "auto-approved");
cmd3.Parameters.AddWithValue("#date", nextDate);
cmd3.Parameters.AddWithValue("#site", lblsite.Text);
cmd3.Parameters.AddWithValue("#skill", lblskill.Text);
cmd3.Parameters.AddWithValue("#shift", lblshift.Text);
cmd3.Parameters.AddWithValue("#status", "pending");
string chklog = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd1 = new MySqlCommand(chklog, conn);
cmd1.Parameters.AddWithValue("#date", nextDate);
cmd1.Parameters.AddWithValue("#login", Label1.Text);
cmd1.Parameters.AddWithValue("#stat", "auto-approved");
conn.Open();
string count = cmd2.ExecuteScalar().ToString();
string count2 = cmd3.ExecuteScalar().ToString();
var slot2 = Convert.ToInt32(count);
Int32 slot3 = hcount1 - slot2;
string slot4 = slot3.ToString();
MySqlDataReader dr1 = cmd1.ExecuteReader();
MySqlConnection con = new MySqlConnection(MyConString);
string chklog1 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd4 = new MySqlCommand(chklog1, con);
cmd4.Parameters.AddWithValue("#date", nextDate);
cmd4.Parameters.AddWithValue("#login", Label1.Text);
cmd4.Parameters.AddWithValue("#stat", "pending");
con.Open();
MySqlDataReader dr2 = cmd4.ExecuteReader();
MySqlConnection con2 = new MySqlConnection(MyConString);
string chklog2 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd5 = new MySqlCommand(chklog2, con2);
cmd5.Parameters.AddWithValue("#date", nextDate);
cmd5.Parameters.AddWithValue("#login", Label1.Text);
cmd5.Parameters.AddWithValue("#stat", "rejected");
con2.Open();
MySqlDataReader dr3 = cmd5.ExecuteReader();
MySqlConnection con3 = new MySqlConnection(MyConString);
string chklog3 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd6 = new MySqlCommand(chklog3, con3);
cmd6.Parameters.AddWithValue("#date", nextDate);
cmd6.Parameters.AddWithValue("#login", Label1.Text);
cmd6.Parameters.AddWithValue("#stat", "agent-withdrawn");
con3.Open();
MySqlDataReader dr4= cmd6.ExecuteReader();
if (nextDate == e.Day.Date)
{
if (dr1.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.LightGreen;
}
else if (dr2.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.Gold;
}
else if (dr3.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.Tomato;
}
else if (dr4.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
conn.Close();
con.Close();
con2.Close();
con3.Close();
samples.Add(new Sample { Date = nextDate, SlotAvailable = slot4, Pending = count2 });
}
if (samples.Any(x => x.Date == e.Day.Date))
{
string weekoff = lblweekoff.Text;
List<string> offday = (lblweekoff.Text).Split(',').ToList();
if (offday.Contains(e.Day.Date.ToString("ddd")))
{
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Week-Off </p>"));
}
else
{
caldisp(e);
}
}
else
{
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Target not set! </p>"));
}
}
}
How can I make this process faster? Any help is appreciated, Thanks in advance!
You have 6 SQL queries into foreach statement, if you have 10 rows in dsleaveplanner the program will execute 60 SQL queries. this number of SQL queries will have a negative impact on performance.
try to retrieve all data before your foreach statement and stock data into lists (memory) then use it within your foreach

Asp calendar with datasource repeats the label

I have an asp calendar linked to datasource and it fetches the count of number of times a date has repeated in the data table and display it on the calendar. but if there are 2 dates of the same month is on the mysql table then the labels appears twice and thrice if there are 3 dates and so on as shown in the image below.
The code for this is shown below
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
cal2.VisibleDate = DateTime.Today;
FillLeaveplannerDataset();
}
}
protected void FillLeaveplannerDataset()
{
cal2.VisibleDate = cal2.TodaysDate;
DateTime firstDate = new DateTime(cal2.VisibleDate.Year, cal2.VisibleDate.Month, 1).AddDays(-6);
DateTime lastDate = new DateTime(cal2.VisibleDate.Date.AddMonths(1).Year, cal2.VisibleDate.Date.AddMonths(1).Month, 1).AddDays(7);
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (cal2.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = cal2.VisibleDate.Year + 1;
}
else
{
monthNumber = cal2.VisibleDate.Month + 1;
yearNumber = cal2.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
DataSet dsMonth = new DataSet();
MySqlConnection con = new MySqlConnection("Server=localhost;Database=mydb;Uid=myid;Pwd=abc123;");
string caldate = "Select date From approved Where date >= #firstDate And date <= #lastDate Group By date";
MySqlCommand cmd = new MySqlCommand(caldate, con);
cmd.Parameters.AddWithValue("#firstDate", firstDate);
cmd.Parameters.AddWithValue("#lastDate", lastDate);
MySqlDataAdapter mysqlDataAdapter = new MySqlDataAdapter(cmd);
try
{
mysqlDataAdapter.Fill(dsMonth);
}
catch { }
return dsMonth;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=mydb;Uid=myid;Pwd=abc123;");
string cntdate = "SELECT COUNT(date) FROM approved WHERE date = #date";
string cntdate2 = "SELECT COUNT(date) FROM pending WHERE date = #date";
MySqlCommand cmd2 = new MySqlCommand(cntdate, conn);
MySqlCommand cmd3 = new MySqlCommand(cntdate2, conn);
cmd2.Parameters.AddWithValue("#date", nextDate);
cmd3.Parameters.AddWithValue("#date", nextDate);
conn.Open();
string count = cmd2.ExecuteScalar().ToString();
string count2 = cmd3.ExecuteScalar().ToString();
var slot2 = Convert.ToInt32(count);
Int32 slot3 = 10 - slot2;
string slot4 = slot3.ToString();
conn.Close();
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Orange;
Environment.NewLine.ToString();
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p></p>Slot available:"));
e.Cell.Controls.Add(new LiteralControl(slot4));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending:"));
e.Cell.Controls.Add(new LiteralControl(count2));
}
else
{
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Slot available: 10</p>"));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending: 0"));
}
}
}
}
protected void Calendar1_VisibleMonthChanged(object sender,
MonthChangedEventArgs e)
{
DateTime firstDate = e.NewDate.AddDays(-7);
DateTime lastDate = e.NewDate.AddMonths(1).AddDays(7);
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
What I want is if there is no data for a date i want the default value Slot avalable: 10 and Pending: 0 to be displayed. And I want the slot available and pending to be displayed only once in each date. What am I missing here?
Thanks in advance
First of all create one sample class with your name
class Sample
{
public DateTime Date { get; set; }
public int SlotAvailable { get; set; }
public int Pending { get; set; }
}
And create a List<Sample>
List<Sample> samples = new List<Sample>();
Then change your foreach like
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=mydb;Uid=myid;Pwd=abc123;");
string cntdate = "SELECT COUNT(date) FROM approved WHERE date = #date";
string cntdate2 = "SELECT COUNT(date) FROM pending WHERE date = #date";
MySqlCommand cmd2 = new MySqlCommand(cntdate, conn);
MySqlCommand cmd3 = new MySqlCommand(cntdate2, conn);
cmd2.Parameters.AddWithValue("#date", nextDate);
cmd3.Parameters.AddWithValue("#date", nextDate);
conn.Open();
string count = cmd2.ExecuteScalar().ToString();
string count2 = cmd3.ExecuteScalar().ToString();
var slot2 = Convert.ToInt32(count);
Int32 slot3 = 10 - slot2;
string slot4 = slot3.ToString();
conn.Close();
samples.Add(new Sample { Date = nextDate, SlotAvailable = slot4, Pending = count2 });
}
And then simply check if the e.Day.Date is present in our date in List<Sample>s date like
if (samples.Any(x => x.Date == e.Day.Date))
{
e.Cell.BackColor = System.Drawing.Color.Orange;
Environment.NewLine.ToString();
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p></p>Slot available:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().SlotAvailable.ToString()));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().Pending.ToString()));
}
else
{
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Slot available: 10</p>"));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending: 0"));
}
Output:

Inserting mysql datas between 2 dates using c#

<asp:TextBox ID="txtstartdate" class="form-control" autocomplete="off" CssClass="datepicker1" runat="server"></asp:TextBox>
<asp:TextBox ID="txtenddate" class="form-control" autocomplete="off" CssClass="datepicker2" runat="server"></asp:TextBox>
<asp:TextBox id="txtreason" TextMode="multiline" runat="server" />
<asp:Button ID="submit" CssClass="login" runat="server" Text="Submit" OnClick="Submit_click" />
Using the Submit_click I want to insert data into table between the 2 dates selected on txtstartdate and txtenddate. txtreason should repeat for all the dates on the table.
For example if select dates 07/30/2018 and 08/04/2018 on txtstartdate and txtenddate and enter "hello" as reason for txtreason, I should get all the dates between 07/30/2018 and 08/04/2018 in the ldate column on the data table and hello should be repeated on reason column for 6 times for each individual dates.
The below method works like a charm if you change date format.
protected void Submit_click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(txtstartdate.Text);
DateTime enddate = Convert.ToDateTime(txtenddate.Text);
for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
{
try
{
string MyConString = "SERVER=localhost;DATABASE=mydb;UID=myid;PASSWORD=abc123;";
MySqlConnection connection = new MySqlConnection(MyConString);
string cmdText = "INSERT INTO approved(agentlogin ,leavetype ,date ,time, reason)VALUES ( #login, #type, #date, 'Full day', #reason)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("#login", Label1.Text);
cmd.Parameters.AddWithValue("#type", ddlleavetype.Text);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#reason", txtreason.Text);
connection.Open();
int result = cmd.ExecuteNonQuery();
connection.Close();
//lblError.Text = "Data Saved";
}
catch (Exception)
{
Console.Write("not entered");
//lblError.Text = ex.Message;
}
}
}
This is why you should use models, and utilise the proper types rather than keep everything a string.
While not perfect, a step in the right direction would be something like this :
(Keep in mind that i haven't solved every single problem. there is plenty of room for improvement)
public class DateRangeModel
{
public DateTime From {get; set;}
public DateTime To {get; set;}
public IEnumerable<DateTime> DaysInRange {
get{
for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
yield date;
}
}
}
public DateRangeModel(string from, string to)
{
From = GetDate(from);
To = GetDate(to);
}
private static DateTime GetDate(string string_date)
{
DateTime dateValue;
if (DateTime.TryParse(string_date, out dateValue))
return dateValue;
else
throw new Exception("Unable to convert '{0}' to a date.", string_date);
}
}
protected void Submit_click(object sender, EventArgs e)
{
DateRangeModel dateRange = new DateRangeModel(txtstartdate.Text, txtenddate.Text);
OleDbConnection scn = new OleDbConnection();
scn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=/mysource;";
foreach(var dt in dateRange.DaysInRange)
{
OleDbCommand scmd = new OleDbCommand("Insert query", scn);
scmd.CommandType = CommandType.Text;
scmd.Parameters.Clear();
scmd.Parameters.AddWithValue("#date1", dt);
scmd.Parameters.AddWithValue("reason", txtreason);
//etc (finish your insert stmt here).
}
}
Use the below method to change the date format. Hope this helps
protected void Submit_click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(txtstartdate.Text);
DateTime enddate = Convert.ToDateTime(txtenddate.Text);
for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
{
try
{
var shtdate = date.ToShortDateString();
string MyConString = "SERVER=localhost;DATABASE=mydb;UID=myid;PASSWORD=abc123;";
MySqlConnection connection = new MySqlConnection(MyConString);
string cmdText = "INSERT INTO approved(agentlogin ,leavetype ,date ,time, reason)VALUES ( #login, #type, #date, 'Full day', #reason)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("#login", Label1.Text);
cmd.Parameters.AddWithValue("#type", ddlleavetype.Text);
cmd.Parameters.AddWithValue("#date", shtdate);
cmd.Parameters.AddWithValue("#reason", txtreason.Text);
connection.Open();
int result = cmd.ExecuteNonQuery();
connection.Close();
//lblError.Text = "Data Saved";
}
catch (Exception)
{
Console.Write("not entered");
//lblError.Text = ex.Message;
}
}
}

SqlDateTime overflow error in asp.net

I want to insert the (Day,Date,Time) from a Calendar and TimePicker a in my DB but I got this error
"SqlDateTime overflow"
Date access code:
public void InsertExam(SqlCommand cmd)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "InsertExam";
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
con.Close();
}
Business
public void InsertExam_record()
{
cmd.Parameters.AddWithValue("#EWeekday", EWeekday);
cmd.Parameters.AddWithValue("#BegainTime", BegainTime);
cmd.Parameters.AddWithValue("#EndTime", EndTime);
cmd.Parameters.AddWithValue("#Duration", Duration);
cmd.Parameters.AddWithValue("#DateAD", DateAD);
cmd.Parameters.AddWithValue("#CourseID", CourseID);
cmd.Parameters.AddWithValue("#SemsterID", SemsterID);
dal.InsertExam(cmd);
}
CS
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DateTime dt = DateTime.Parse("08:30 AM");
MKB.TimePicker.TimeSelector.AmPmSpec am_pm;
if (dt.ToString("tt") == "AM")
{
am_pm = MKB.TimePicker.TimeSelector.AmPmSpec.AM;
}
else
{
am_pm = MKB.TimePicker.TimeSelector.AmPmSpec.PM;
}
TimeSelector1.SetTime(dt.Hour, dt.Minute, am_pm);
}
CourseGridView.DataBind();
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToString("ddd", new System.Globalization.CultureInfo("ar-SA"));
TextBox2.Text= Calendar1.SelectedDate.ToString("yyyy/MM/dd", new System.Globalization.CultureInfo("ar-SA"));
TextBox3.Text = Calendar1.SelectedDate.ToString("yyyy/MM/dd");
}
protected void Submit(object sender, EventArgs e)
{
DateTime start = DateTime.Parse(string.Format("{0}:{1}", TimeSelector1.Hour, TimeSelector1.Minute));
DateTime end = DateTime.Parse(string.Format("{0}:{1}", TimeSelector2.Hour, TimeSelector2.Minute));
TimeSpan du = end - start;
double r = du.TotalHours;
EndTime.Text = r.ToString();
b.EWeekday = TextBox1.Text;
b.BegainTime = Convert.ToDateTime(start);
b.EndTime = Convert.ToDateTime(end);
b.Duration = Convert.ToInt32(r);
b.DateAD = Convert.ToDateTime(TextBox3.Text);
b.CourseID = Convert.ToInt32(CourseGridView.SelectedValue);
b.SemsterID = Convert.ToInt32(SemsterList.SelectedValue);
b.InsertExam_record();
}
and this is my Stored Procedure
[dbo].[InsertExam]
-- Add the parameters for the stored procedure here
#EWeekday NVARCHAR (50),
#BegainTime Time,
#EndTime Time,
#Duration INT,
#DateAD Date,
#CourseID INT,
#SemsterID INT
AS
BEGIN
INSERT INTO Exam
( EWeekday, BegainTime, EndTime, Duration, DateAD, CourseID, SemsterID)
VALUES (#EWeekday,#BegainTime,#EndTime,#Duration,#DateAD,#CourseID,#SemsterID)
END

error when generating gridview

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/

Categories