I have an sql table that returns financial year start_date and end_date, so now i want to use that query to dropdownlist of months starting from april until march.
And based on the selected month i get the revenue for that month.So the query for calculating financial year only return 2018/04/01 as start_date and 2019/03/31 as end_date, so bare in mind it's not months, just a date .Of course i will be connected to a server and choose my database and table. see what i tried below.
public class Fyear
{
public string FiscalY_Start { get; set; }
public string FiscalY_End { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
//Data Source=cntrra02-sql-rs;Initial Catalog=Training_Database;Integrated Security=True
DateTime start_date;
DateTime end_date;
List<Fyear> list = new List<Fyear>();
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(#"Data Source=serv_name;Initial Catalog=Database_name;Integrated Security=True");
SqlCommand cmd = new SqlCommand(#"SELECT [ST_FI], [END_FY] FROM [FiscalYear]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
start_date = Convert.ToDateTime(rdr["ST_FI"]);
end_date = Convert.ToDateTime(rdr["END_FY"]);
//DropDownList1.Items.Add(start_date.ToString());
//int count = 0;
while (start_date <= end_date)
{
//count++;
//list.Add(new Fyear{ FiscalY_Start = start_date.ToString("MMMM")});
start_date = start_date.AddMonths(1);
DropDownList1.Items.Add(start_date.ToString());
}
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
// DropDownList1.DataSource = dt;
// DropDownList1.DataBind();
}
Related
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 am trying to run multiple queries within a loop. The first query runs ok as I can see it when I step through the code.
However the second query (which is within a loop) is supposed to run depending on the value held from the first. When the loop runs based on that value it seems to be ignoring the query. I put a label to display in place of the query and it displayed so I believe how I have opened/closed my connection is not correct.
c# code:
protected void Page_Load(object sender, EventArgs e)
{
// Get the session of the user
string staffid = Session["StaffId"].ToString();
//Proxy on page load to check IsActive Status
string DefaultConnection = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection = new SqlConnection(DefaultConnection);
myConnection.Open();
//select the userdetail specific to the logged in user using parameterisation
string query = "SELECT ProxyStatus.ProxyStatusId, ProxyStatus.FunctionId, ProxyStatus.StartDate, ProxyStatus.EndDate, ProxyStatus.IsActive FROM ProxyStatus INNER JOIN Staff ON Staff.StaffId = ProxyStatus.Proxee WHERE (Staff.StaffId = #StaffId)";
DateTime thisDay = DateTime.Today;
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#staffid", staffid);
SqlDataReader rdr = myCommand.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
Session["StartDate"] = rdr["StartDate"].ToString();
Session["EndDate"] = rdr["EndDate"].ToString();
Session["ProxyStatusId"] = rdr["ProxyStatusId"].ToString();
Session["FunctionId"] = rdr["FunctionId"].ToString();
// Get the session of StartDate and endate, use the session value in a query to compare against the current date
string startdate = Session["StartDate"].ToString();
string enddate = Session["EndDate"].ToString();
string proxystatus = Session["ProxyStatusId"].ToString();
DateTime startdatedata = Convert.ToDateTime(startdate);
DateTime enddatedata = Convert.ToDateTime(enddate);
if (startdatedata > thisDay)
{
string DefaultConnection2 = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(DefaultConnection2);
myConnection2.Open();
string query2 = "UPDATE ProxyStatus SET ProxyStatus.IsActive = 'False' WHERE ProxyStatus.ProxyStatusId = #proxystatus";
myCommand.Parameters.AddWithValue("#newproxystatus", proxystatusnew);
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
}
}
}
else
{
rdr.Close();
}
}
}
}
Shouldn't the lines be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand.ExecuteNonQuery();
be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
instead? The first "myCommand" will still be in use with "rdr".
I am trying show some data from a database to a combobox based on another combobox selection with this code:
private void metroComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dt = new DataSet();
try
{
DateTime startDate = Convert.ToDateTime(metroLabel8.Text);
DateTime endDate = Convert.ToDateTime(metroLabel9.Text);
// Make sql readable
string sql =
#"Select [LedId],[LedName] from [Ledger] where Date >= #prmStartDate and Date <= #prmEndDate";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
con.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
VoucherLedgerName_combo.DisplayMember = "LedName";
VoucherLedgerName_combo.ValueMember = "LedId";
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
}
}
catch(Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
But i am getting nothing in the second combobox, and I am sure that there is data in the database table Ledger. Can any one please help me to find the issue?
change your SQL statement as below(Date is reserved keyword)
string sql =
#"Select [LedId],[LedName] from [Ledger] where [Date] >= #prmStartDate and [Date] <= #prmEndDate";
You need to give table name when you fill dataset since you are using the name when you set data source
da.Fill(dt, "Ledger");
or set the data source as below
VoucherLedgerName_combo.DataSource = dt.Tables[0];
DataRow dr = dt.NewRow();
dr["Ledger"] = "--Select All--";
dt.Rows.InsertAt(dr, 0);
You can change from
da.Fill(dt);
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
to
da.Fill(dt, "Ledger");
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"].DefaultView;
else
VoucherLedgerName_combo.DataSource = dt.Tables[0].DefaultView;
or
VoucherLedgerName_combo.DataSource = dt;
I am trying to get data in gridview on the basis of the date that is entered in dateTimePicker. But, I am getting null reference runtime error on if condition where I have used equals function to compare two strings.
ReportFrom.cs
private void button1_Click(object sender, EventArgs e)
{
string date = dateTimePicker.Value.ToShortDateString();
reportLayer.MakeDailyReport(date, dataGridViewReport);
}
ReportLayer.cs
private SqlConnection con = new SqlConnection("Data Source=CHAMP-PC;Initial Catalog=ProcessSale;Integrated Security=True");
private SqlCommand cmd;
private SqlDataAdapter adapt;
public void MakeDailyReport(string givenDate, DataGridView view)
{
try
{
con.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
object dateObject = cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject);
string givenDateString = Convert.ToString(givenDate);
// string DBdate = dateObject.ToString();
if (dateObject.Equals(givenDate))
{
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
con.Close();
}
}
Have a look here:
Handling ExecuteScalar() when no results are returned
Additionally: Be careful with the call to Equals(). Currently you are comparing
two strings. One with a ShortDate value One with the default ToString().
Event if the dates are equal, this might return false.
A better solution would be handling both values as DateTime and use the == operator.
Thomas
I am getting a System.Data.SqlClient.SqlException with additional information of an Invalid column name Jun on Fill function while I am entering 19-jun-2016 from the datetimePicker and here is a Jun is a month but it taking it as a column.
ReportForm.cs
public void MakeDailyReport(string givenDate, DataGridView view)
{
con.Open();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
DateTime dateObject = (DateTime)cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject.ToShortDateString());
string givenDateString = Convert.ToString(givenDate);
if (dateObjectstring == givenDateString)
{
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
Don't use string concatenation to build your query but sql parameters with the correct type. That will also prevent you from sql injection and other possible issues (like this one).
adapt = new SqlDataAdapter("SELECT [Date] FROM FinalSales where [Date] = #givenDate", con);
var dateParameter = adapt.SelectCommand.Parameters.Add("#givenDate", SqlDbType.DateTime);
dateParameter.Value = dateTimePicker.Value.Date; // not string but the correct type DateTime
Note that i've also used dateTimePicker.Value.Date to ignore the time portion.