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:
Related
I'm checking if a seal number exists in the database table, however when I use either the stored procedure or behind it doesn't work. The stored procedure produce the error message but if it doesn't exist it tells that I didn't supply a value, when the value is there. And from the code behind it is giving this error: Collection was modified; enumeration operation may not execute.
Code Behind
protected void showData()
{
#region Seal
SqlCommand R = new SqlCommand("PP_SealRecord", objConnection);
R.CommandType = CommandType.StoredProcedure;
R.Parameters.AddWithValue("#loadSheetNum", dispatchSheetNo);
objConnection.Open();
SqlDataReader Reader = R.ExecuteReader();
int maximumTextBoxCount = 7;
if (Reader.Read())
{
ControlCache = new List<Control>();
phSealNum.Controls.Clear();
for (int i = 0; i < maximumTextBoxCount; i++)
{
TextBox txt = new TextBox();
string index = string.Format("seal{0}", i + 1);
if (Reader[index] != DBNull.Value)
{
txt.Text = (string)Reader[index];
}
else
{
continue;
}
phSealNum.Controls.Add(txt);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(txt);
txt.Width = 100;
//txt.Enabled = false;
}
}
Reader.Close();
objConnection.Close();
#endregion
}
protected void Update_Click(object sender, EventArgs e)
{
#region Seal Data
string str = null;
int countseal = 0;
foreach (TextBox textBox in phSealNum.Controls.OfType<TextBox>())
{
string constr = ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ConnectionString;
using (SqlCommand comm = new SqlCommand("PP_CountSeal"))
{
comm.Connection = con;
con.Open();
comm.CommandType = CommandType.StoredProcedure;
str = textBox.Text.TrimEnd();
comm.CommandType = CommandType.StoredProcedure;
string seal1 = string.Format("#seal{0}", countseal);
comm.Parameters.AddWithValue(seal1, str);
int count = (int)cmd.ExecuteScalar();
string name = HttpContext.Current.User.Identity.Name;
if (count > 0)
{
SqlCommand command = new SqlCommand("PP_SealRecord", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#loadSheetNum", dispatchSheetNo);
SqlDataReader data = command.ExecuteReader();
if (data.Read())
{
string previousseal1 = Convert.ToString(data["seal1"]);
string previousseal2 = Convert.ToString(data["seal2"]);
string previousseal3 = Convert.ToString(data["seal3"]);
string previousseal4 = Convert.ToString(data["seal4"]);
string previousseal5 = Convert.ToString(data["seal5"]);
string previousseal6 = Convert.ToString(data["seal6"]);
string previousseal7 = Convert.ToString(data["seal7"]);
EditSeal(dispatchSheetNo, previousseal1, previousseal2, previousseal3, previousseal4, previousseal5, previousseal6, previousseal7, name);
}
}
else
{
// INSERT STATEMENT
CreateSeal(loadsheet, CreatedBy);
}
#endregion
}
//Creates history when seal is updated
protected void InsertSealHistory()
{
SqlConnection con = new SqlConnection(connection); //SQL Connection
con.Open();
#region Get Seal Record
SqlCommand cmd = new SqlCommand("PP_SealDataRecord", con);
cmd.CommandType = CommandType.StoredProcedure; //SQL Command Type is Stored Procedure
cmd.Parameters.AddWithValue("#loadsheetnum", dispatchSheetNo);
SqlDataReader dr = cmd.ExecuteReader();
string sealNumber = "";
string CreatedBy = "";
DateTime? DateCreated = null;
while (dr.Read()) {
sealNumber = dr["sealNumber"].ToString();
CreatedBy = dr["CreatedBy"].ToString();
DateCreated = Convert.ToDateTime(dr["DateCreated"].ToString());
}
dr.Close();
con.Close();
#endregion
#region Insert Seal History
con.Open();
SqlCommand I = new SqlCommand("PP_CreateSealDataHistory", con);
I.CommandType = CommandType.StoredProcedure;
I.Parameters.AddWithValue("#LoadSheetNum", dispatchSheetNo);
I.Parameters.AddWithValue("#SealNumber", sealNumber);
I.Parameters.AddWithValue("#CreatedBy", CreatedBy);
I.Parameters.AddWithValue("#DateCreated",DateCreated);
I.ExecuteNonQuery();
con.Close();
#endregion
}
protected void EditSeal(string num, string a, string b, string c, string d, string e, string f, string g, string user)
{
SqlConnection con = new SqlConnection(connection); //SQL Connection
con.Open();
int maxPossibleTextBoxCount = 7;
int selectedTextBoxCount = phSealNum.Controls.OfType<TextBox>().Count();
int emptyTextBoxCount = maxPossibleTextBoxCount - selectedTextBoxCount;
SqlCommand U = new SqlCommand("PP_updateSeal", con);
U.CommandType = CommandType.StoredProcedure;
U.Parameters.AddWithValue("#loadsheetNum", num);
foreach (TextBox textBox in phSealNum.Controls.OfType<TextBox>())
{
if (!Regex.IsMatch(textBox.Text.Replace(" ", ""), #"(^([0-9]*|\d*\d{1}?\d*)$)"))
{
lblError.Text = "Please enter only numeric values for seal number";
return;
}
else if (textBox.Text == "")
{
lblError.Text = "Please enter seal number";
return;
}
else
{
countSeal += 1;
Session["CountSeal"] = countSeal;
if (countSeal == 1)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, a);
}
else if (countSeal == 2)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, b);
}
else if (countSeal == 3)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, c);
}
else if (countSeal == 4)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, d);
}
else if (countSeal == 5)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, e);
}
else if (countSeal == 6)
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, f);
}
else
{
string seal = string.Format("#previous_seal{0}", countSeal);
U.Parameters.AddWithValue(seal, g);
}
string seal1 = string.Format("#seal{0}", countSeal);
U.Parameters.AddWithValue(seal1, textBox.Text);
}
}
// Here we add the parameters for the non-selected textboxes.
if (emptyTextBoxCount > 0)
{
for (int i = 0; i < emptyTextBoxCount; i++)
{
countSeal += 1;
Session["CountSeal"] = countSeal;
string seal = string.Format("#previous_seal{0}", countSeal);
string seal1 = string.Format("#seal{0}", countSeal);
U.Parameters.AddWithValue(seal, System.DBNull.Value);
U.Parameters.AddWithValue(seal1, System.DBNull.Value);
}
}
U.Parameters.AddWithValue("#lastUser", user);
//U.Parameters.Add("#outmessage", SqlDbType.Char, 500);
//U.Parameters["#outmessage"].Direction = ParameterDirection.Output;
U.ExecuteNonQuery();
//lblError.Text = (string)U.Parameters["#outmessage"].Value;
con.Close();
showData();
}
protected void CreateSeal(string num, string user)
{
SqlConnection con = new SqlConnection(connection); //SQL Connection
con.Open();
SqlCommand U = new SqlCommand("PP_CreateSealNumber", con);
U.CommandType = CommandType.StoredProcedure;
int counter = 1;
int maxPossibleTextBoxCount = 7;
int selectedTextBoxCount = phSealNum.Controls.OfType<TextBox>().Count();
int emptyTextBoxCount = maxPossibleTextBoxCount - selectedTextBoxCount;
foreach (TextBox textBox in phSealNum.Controls.OfType<TextBox>())
{
if (!Regex.IsMatch(textBox.Text, #"(^([0-9]*|\d*\d{1}?\d*)$)"))
{
lblError.Text = "Please enter only numeric values for seal number";
return;
}
else
{
string seal = string.Format("#seal{0}", counter++);
//command.Parameters.AddWithValue(seal, textBox.Text);
U.Parameters.AddWithValue(seal, textBox.Text);
}
}
// Here we add the parameters for the non-selected textboxes.
if (emptyTextBoxCount > 0)
{
for (int i = 0; i < emptyTextBoxCount; i++)
{
string seal = string.Format("#seal{0}", counter++);
//command.Parameters.AddWithValue(seal, textBox.Text);
U.Parameters.AddWithValue(seal, DBNull.Value);
//command.Parameters.AddWithValue($"#seal{counter++}", DBNull.Value);
}
}
U.Parameters.AddWithValue("#loadsheetNum", num);
U.Parameters.AddWithValue("#lastUser", user);
U.ExecuteNonQuery();
con.Close();
showData();
}
protected void TotalSeal_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
//Populates the amount of textbox based on the value selected from the drop down
public void populate()
{
//ControlCache = new List<Control>();
//phSealNum.Controls.Clear();
int targetCount = Convert.ToInt32(TotalSeal.SelectedItem.Value);
int currentItems = phSealNum.Controls.OfType<TextBox>().Count();
int totalitems = targetCount - currentItems;
if (totalitems <= 7)
{
for (int i = 0; i < totalitems; i++)
{
TextBox tx = new TextBox();
tx.MaxLength = 10;
tx.Width = 100;
phSealNum.Controls.Add(tx);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(tx);
}
}
else
{
lblError.Text = targetCount + " exceeds number of seals";
}
}
Is your collection phSealNum.Controls.OfType() is getting modified when your iterating in loop? Please check that let me know.
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
I want to create the attached task scheduler using asp.net and C#.
In SQL Server I have a table with these columns:
InstituteId, InstituteName, Address,
CareerDay2017 (date), CareerDay2018 (date), CareerDay2019 (date)
Dropdown list has values 2017, 2018, 2019. A button should be next to the dropdownlist.
When we select the year from dropdown list and click the button particular data should be retrieved and displayed as the image.
The career day details should be retrieved and colored the particular cell.
This is what I have tried, but it is incorrect. Hope you have taken my idea and help me.
SqlConnection con = new SqlConnection(#"Data Source=NAWODA;Initial Catalog=InternsDB;Integrated Security=True");
SqlCommand cmd;
SqlDataReader sdr,sdr1, sdr2;
String query;
DateTime current = DateTime.Now;
String dateColumn;
StringBuilder table = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
searchDetailPanel.Visible = false;
searchTaskPanel.Visible = false;
if (!Page.IsPostBack)
{
con.Open();
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2018) = '2018'
ORDER BY InstituteId";
cmd = new SqlCommand(query, con);
sdr1 = cmd.ExecuteReader();
}
setData(sdr1, currentDetailPanel);
{
query = #"SELECT CareerDay2017, CareerDay2018, CareerDay2019
FROM Institution
ORDER BY InstituteId";
cmd = new SqlCommand(query, con);
sdr2 = cmd.ExecuteReader();
}
createYearTable(sdr1, sdr2, currentTaskPanel);
}
}
private void setData(SqlDataReader sdr, Panel DetailPanel1)
{
table.Append("<table>");
table.Append("<tr><th>Institute ID</th> <th>Institute Name</th>");
table.Append("</tr>");
if (sdr.HasRows)
{
while (sdr.Read())
{
table.Append("<tr>");
table.Append("<td>" + sdr[0] + "</td>");
table.Append("<td>" + sdr[1] + "</td>");
table.Append("</tr>");
}
}
table.Append("</table>");
DetailPanel1.Controls.Add(new Literal { Text = table.ToString() });
sdr.Close();
sdr.Dispose();
}
private void createYearTable(SqlDataReader sdr1,SqlDataReader sdr2, Panel DetailPanel2)
{
int currentYear = Int32.Parse(current.ToString("yyyy"));
table.Append("<table>");
//****filling the year
table.Append("<tr>");
for (int i = 1; i <= 12; i++)
{
table.Append("<td>" + Convert.ToString(currentYear) + "</td>");
}
table.Append("</tr>");
//****filling the month
table.Append("<tr>");
for (int j = 1; j <= 12; j++)
{
int monthString = j;
table.Append("<td>" +getMonthName(monthString) + "</td>");
}
table.Append("</tr>");
//****data cell filling
if (sdr2.HasRows)
{
while (sdr2.Read())
{
table.Append("<tr>");
if (yearDropDownList.SelectedValue == "2017")
{
dateColumn = sdr2[5].ToString();
DateTime careerFairDate = Convert.ToDateTime(dateColumn);
int monthNo = Int32.Parse(careerFairDate.ToString("MM"));
int dateNo = Int32.Parse(careerFairDate.ToString("dd"));
for (int j = 1; j <= 12; j++)
{
if (monthNo == j)
{
table.Append("<td>");
Label lbl1 = new Label();
lbl1.Text = "On" + dateNo;
table.Append("</td>");
}
else
{
table.Append("<td>");
Label lbl2 = new Label();
table.Append("</td>");
}
}
}
table.Append("</tr>");
}
table.Append("</table>");
DetailPanel2.Controls.Add(new Literal { Text = table.ToString() });
sdr2.Close();
sdr2.Dispose();
}
}
protected String getMonthName(int i)
{
String[] monthName = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
return monthName[i - 1];
}
protected void searchBtn_Click(object sender, EventArgs e)
{
currentDetailPanel.Visible = false;
currentTaskPanel.Visible = false;
searchDetailPanel.Visible = true;
searchTaskPanel.Visible = true;
con.Open();
if (yearDropDownList.SelectedValue == "2018")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2018) = '2018'
ORDER BY InstituteId";
}
else if (yearDropDownList.SelectedValue == "2017")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2017) = '2017'
ORDER BY InstituteId";
}
else if (yearDropDownList.SelectedValue == "2019")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2019) = '2019'
ORDER BY InstituteId";
}
cmd = new SqlCommand(query, con);
sdr = cmd.ExecuteReader();
setData(sdr, searchDetailPanel);
DateTime current = DateTime.Now;
createYearTable(sdr,sdr2,searchTaskPanel);
}
As for the UI part, you need to place a breakpoint in the method that draws your UI and step through it while it is reading your data. You need to learn how to debug you code.
Just based off what you have posted, I think you have a bigger issue, you should not be declaring a SqlConnection at the class level, it should be in a method somewhere. For example:
public void GetCalendarData(int year)
{
// You need to use a parameter for the year instead of hard-coding it (note the #year)
string strCmd = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CarrerDay2018) = #year
ORDER BY InstituteId";
using(var conn = new SqlConnection(connString))
using(var cmd = new SqlCommand(strCmd))
{
// add the #year parameter to the command
cmd.Parameters.AddWithValue("#year", year);
conn.Open();
var reader = cmd.ExecuteReader();
// setdata, createYearTable, etc.
conn.Close();
}
}
This way you are not holding a connection to the database for any longer than you need to. Also, I have put the connection and the command inside using statements, meaning that they will be disposed of properly by the garbage collector.
I'm having problem setting the vertical scroll position. I have followed this similar question and I get the expected result for CellDoubleClick Event. But for KeyDown Event, where the user will press Enter key, it resets the vertical scroll position at the top
These are my CellDouble Click and KeyDown events.
private void dataGridSrch_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
addToSell();
}
}
private void dataGridSrch_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
addToSell();
}
This is my addToSell function, this function will call after that will update the DataGridView.
public void addToSell()
{
if (dataGridSrch.SelectedRows.Count > 0)
{
DataRow row = (dataGridSrch.SelectedRows[0].DataBoundItem as DataRowView).Row;
if (Convert.ToInt32(row["Stock"].ToString()) > 0)
{
string sellProd = row["Brand"].ToString() + " " + row["Part No."].ToString();
int sellQty = Convert.ToInt32(numSell.Value);
string sellUnit = row["Unit"].ToString();
double sellPrice = double.Parse(row["Price"].ToString()) * sellQty;
double sPrice = double.Parse(row["Price"].ToString());
dataGridSales.Rows.Add(sellProd, sellQty, sellUnit, sellPrice, sPrice, row["Part No."].ToString(), row["Stock"].ToString());
int count = 0;
double total = 0;
for (int i = 0; i < dataGridSales.Rows.Count; i++)
{
total += Convert.ToDouble(dataGridSales.Rows[i].Cells[3].Value);
count += Convert.ToInt32(dataGridSales.Rows[i].Cells[1].Value);
}
lblTotAmt.Text = "Total Amount: " + total.ToString("C2");
lblTotItem.Text = "Total Items: " + count;
amount = total;
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[products]
SET Stock = Stock - '" + sellQty + "' WHERE [Part No.] = '" + row["Part No."] + "'", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
>>>>>>>>>>>>>>>>after(); //THIS IS WHERE AFTER FUNCTION IS CALLED
}
else
{
MessageBox.Show("You dont have any stock for the selected item, please restock immediately.", "Please restock", MessageBoxButtons.OK);
}
}
if (dataGridSales.Rows.Count > 0)
{
cmbMOP.Enabled = true;
}
}
And this is my after function.
public void after()
{
string item = cmbItem.Text;
string brand = cmbBrand.Text;
string part = txtPart.Text;
string manu = cmbMan.Text;
string car = cmbCar.Text;
string year = cmbYr.Text;
conn.Open();
{
int index = dataGridSrch.SelectedRows[0].Index;
>>>>>>>>>>>>int scrollPos = dataGridSrch.FirstDisplayedScrollingRowIndex; //GET THE SCROLL POSITION
string sel = #"SELECT * FROM[dbo].[products] WHERE 1=1";
using (SqlCommand cmd = new SqlCommand())
{
if (!string.IsNullOrEmpty(item))
{
sel += " AND Item = #Item";
cmd.Parameters.Add("#Item", SqlDbType.VarChar).Value = item;
}
if (!string.IsNullOrEmpty(brand))
{
sel += " AND Brand = #Brand";
cmd.Parameters.Add("#Brand", SqlDbType.VarChar).Value = brand;
}
if (!string.IsNullOrEmpty(part))
{
sel += " AND [Part No.] = #Part";
cmd.Parameters.Add("#Part", SqlDbType.VarChar).Value = part;
}
if (!string.IsNullOrEmpty(manu))
{
sel += " AND Manufacturer = #Manufacturer";
cmd.Parameters.Add("#Manufacturer", SqlDbType.VarChar).Value = manu;
}
if (!string.IsNullOrEmpty(car))
{
sel += " AND Car = #Car";
cmd.Parameters.Add("#Car", SqlDbType.VarChar).Value = car;
}
if (!string.IsNullOrEmpty(year))
{
sel += " AND Year = #Year";
cmd.Parameters.Add("#Year", SqlDbType.VarChar).Value = year;
}
cmd.CommandText = sel;
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
DataView dv = dt.DefaultView;
sda.Fill(dt);
dataGridSrch.DataSource = dt;
dv.Sort = "Item, Brand, Manufacturer, Car, Year, Price ASC ";
dataGridSrch.Columns["Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridSrch.Columns["Price"].DefaultCellStyle.Format = "C2";
dataGridSrch.Columns["Stock"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridSrch.Rows[index].Selected = true;
>>>>>>>>>>>>>>>>>>>>dataGridSrch.FirstDisplayedScrollingRowIndex = scrollPos; //AFTER UPDATE SET THE SCROLL POSITION
typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null,
dataGridSrch, new object[] { true });
}
}
}
conn.Close();
}
I have also change my KeyDown Event to this
private void dataGridSrch_KeyDown(object sender, KeyEventArgs e)
{
int index = dataGridSrch.SelectedRows[0].Index;
int scrollPos = dataGridSrch.FirstDisplayedScrollingRowIndex;
if (e.KeyCode == Keys.Enter)
{
addToSell();
dataGridSrch.Rows[index].Selected = true;
dataGridSrch.FirstDisplayedScrollingRowIndex = scrollPos;
}
}
But still it resets the scroll position.
I have two forms where I have to get the date in the dategridview of the first form:
private void checkinToolStripMenuItem1_Click(object sender, EventArgs e)
{
int rowindex = dgCheckin.CurrentCell.RowIndex;
int reserveindex = 10;
string statindex = dgCheckin.Rows[rowindex].Cells[reserveindex].Value.ToString();
int roomindex = 5;
string roomNum = dgCheckin.Rows[rowindex].Cells[roomindex].Value.ToString();
if (statindex == "Reserved")
{
frmCheckIn recheckin = new frmCheckIn(user, true, roomNum);
recheckin.ShowDialog();
}
else if (statindex == "Cancelled")
{
MessageBox.Show("This " + roomNum + " is already cancelled.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Then the date will put in the datetimepicker in the second form:
public void loadReservation()
{
con.Open();
string reservetable = "tblReservation";
string reservequery = "SELECT*FROM tblReservation WHERE RoomNum = '" + this.roomnum + "' AND Status = 'Reserved'";
da = new SqlDataAdapter(reservequery, con);
da.Fill(ds, reservetable);
int counter = 0;
if (counter < ds.Tables[reservetable].Rows.Count)
{
string dateuse = ds.Tables[reservetable].Rows[counter]["DateOfUse"].ToString();
dtpCheckIn.Text = dateuse;
}
con.Close();
}
But the datetimepicker is not changing/same as what is in the database.