I'm trying to make a query when the user clicks the End Shift button to get the total sales of the day right away without entering the date
I can't figure out how can that be possible, I'm currently using this code for it, which he has to choose 2 dates.
I tried with 1 datetimepicker but I never get a result
can it be done without the user choosing the date?
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) AS 'Total' From Sales where Sdate = #datetime";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
cmd.Parameters.Add("#datetime", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#datetime2", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker2.Value;
cmd.ExecuteNonQuery();
string result = cmd.ExecuteScalar().ToString();
textBox1.Text = #result;
}
Try this
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) From Sales where Sdate = #datetime";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
cmd.Parameters.Add("#datetime", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker1.Value.ToShortDateString();
//cmd.Parameters.Add("#datetime2", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker2.Value;
//cmd.ExecuteNonQuery();
//string result = cmd.ExecuteScalar().ToString();
textBox1.Text = cmd.ExecuteScalar().ToString();
}
can it be done without the user choosing the date?
Yes, take a look at the #M.Rezaeyan answer.
Try
SELECT sum(SQuantity) as 'Total' FROM Sales WHERE Sdate = Date()
Final
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) AS 'Total' From Sales where Sdate = Date()";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
textBox1.Text = cmd.ExecuteScalar().ToString();
}
Related
From the C# code, I am trying to execute a query and pass two parmeters to Access database. Unforunately the parameter name is same beacuse I am passing date parameter. It seems when i exceute the code the first parametr is replaced by the second parameter so for e.g I am passing
Startdate as 1/1/2017 and end date as 1/31/2017
I am still getting the 2016 values.
Below is my code
string ConnString = getConnstring();
string DirectoryPath = getDirectortyPath(year, quater);
StreamWriter file = new StreamWriter(DirectoryPath);
string StartDate = calculateStartDate(year, quater);
string EndDate = CalculateEndDate(year, quater);
string SqlString = "Select * from TestTable where compl_date >= ? and compl_date <= ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("compl_date", StartDate); // startDate can be 1/1/2017
cmd.Parameters.AddWithValue("compl_date", EndDate); // end date could be 1/31/2017
conn.Open();
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
try
{
string FullLine = "";
How can I get the values that are within the above date range.
try like this;
string ConnString = getConnstring();
string DirectoryPath = getDirectortyPath(year, quater);
StreamWriter file = new StreamWriter(DirectoryPath);
string StartDate = calculateStartDate(year, quater);
string EndDate = CalculateEndDate(year, quater);
string SqlString = "Select * from TestTable where compl_date >= #StartDate and compl_date <= #EndDate";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#StartDate", StartDate);
cmd.Parameters.AddWithValue("#EndDate", EndDate);
conn.Open();
....
I would like to sum the following two columns from my database table and display it in form of a chart. My code below will run correct, but show empty chart result. Please help !
c.Open();
DateTime startDateTime = Convert.ToDateTime(textBox1.Text);
DateTime endDateTime = Convert.ToDateTime(textBox2.Text);
string query = "SELECT * FROM People_Tracking WHERE Enter_Exit_Time BETWEEN #startDateTime AND #endDateTime ;";
SqlCommand cmd = new SqlCommand(query, c);
cmd.Parameters.Add("#startDateTime", SqlDbType.DateTime).Value = startDateTime;
cmd.Parameters.Add("#endDateTime", SqlDbType.DateTime).Value = endDateTime;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable t = new DataTable();
adapter.Fill(t);
dataGridView1.DataSource = t;
string query1 = "SELECT Sum(Number_of_Enterance) FROM People_Tracking ;";
string query2 = "SELECT Sum(Number_of_Exits) FROM People_Tracking ;";
this.chart1.Series["DateTime"].Points.AddXY("Number_of_Enterance", query1);
this.chart1.Series["DateTime"].Points.AddXY("Number_of_Exits", query2);
I have this situation: in DataEntryForm I have a dropdownlist, where user selects a letter number, and according to that inserts other related data.
I plan to change letter's status in other table by choosing in dropdownlist automatically.
I am using this code:
SqlParameter answertoparam = new SqlParameter("answerto", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID ='2' where income_number=('" + ansTo + "' )";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
comm.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
Unfortunately, the result is nothing.
Server is not giving error, and it simply refreshes the page that is it.
In your posted code, you are passing the SqlParameter as well as passing the value as raw data. Do either of one and preferably pass it as SqlParameter like
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
Moreover, you have two SqlCommand object in place and calling two ExecuteNonQuery() on them. correct that ... see below
SqlCommand findincomelett = new SqlCommand(commandText, conn); --1
comm.Parameters.Add(answertoparam); --2
conn.Open();
findincomelett.ExecuteNonQuery(); --1
comm.ExecuteNonQuery(); --2
As far as I understand, the issue is that the correct IncomeLetters.docState_ID is not updated to '2'.
You may want to debug and see what value you are getting in :
string ansTo = ddlAnswerTo.SelectedItem.Value;
The record in the database that you are expecting to be updated may not have the record that satisfies the where clause 'income_number = #answertoparam'
I would like to bring you here full code of the page.
Idea is: I have page for enrollment. I am passing data to DB through stored procedure (DataInserter).
Problem is here: during enrollment, user selects from dropdownlist number of the letter he would like to answer to, and in the end, the status of the letter on other table of DB (IncomeLetters.tbl), would change from "pending"('1') to "issued" ('2').
I guess, I could clear my point to you and thank you for your support!
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MaktubhoConnectionString2"].ConnectionString);
using (SqlCommand comm = new SqlCommand("DataInserter", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
SqlParameter employeeparam = new SqlParameter("EmployeeSentIndex", int.Parse(ddlemployee.SelectedItem.Value));
SqlParameter doctypeparam = new SqlParameter("doctype_ID", int.Parse(ddldoctype.SelectedItem.Value));
SqlParameter doccharparam = new SqlParameter("docchar_ID", int.Parse(ddldocchar.SelectedItem.Value));
SqlParameter authorityparam = new SqlParameter("authority", txtauthority.Text);
SqlParameter subjectparam = new SqlParameter("subject", txtsubject.Text);
DateTime dt = DateTime.Now;
string todasdate = dt.ToString("d", CultureInfo.CreateSpecificCulture("de-DE"));
SqlParameter entrydateparam = new SqlParameter("entrydate", todasdate);
string Pathname = "UploadImages/" + Path.GetFileName(FileUpload1.PostedFile.FileName);
SqlParameter imagepathparam = new SqlParameter("image_path", Pathname);
SqlParameter loginparam = new SqlParameter("login", "jsomon");
comm.Parameters.Add(employeeparam);
comm.Parameters.Add(doctypeparam);
comm.Parameters.Add(doccharparam);
comm.Parameters.Add(authorityparam);
comm.Parameters.Add(subjectparam);
comm.Parameters.Add(entrydateparam);
comm.Parameters.Add(imagepathparam);
comm.Parameters.Add(loginparam);
comm.Parameters.Add("#forlabel", SqlDbType.VarChar, 100);
comm.Parameters["#forlabel"].Direction = ParameterDirection.Output;
FileUpload1.SaveAs(Server.MapPath("~/UploadImages/" + FileUpload1.FileName));
string ansTo = ddlAnswerTo.SelectedItem.Value;
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
lblresult.Visible = true;
Image1.Visible = true;
lblresult.Text = "Document number:";
lblnumber.Visible = true;
lblnumber.Text = (string)comm.Parameters["#forlabel"].Value; ;
conn.Close();
}
txtauthority.Text = "";
txtsubject.Text = "";
}
I want to using the code below and display in GridView.
The situation is, when user click on GET CURRENT DATE TRANS, GridView will display the today date as the result. I already insert the GridView id as GridView1
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=AXSQL;Initial Catalog=UniKL;User ID=aten;Password=pass#WORD1";
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";
GridView1.DataBind();
connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
I guess your column SubmittedDateTime is of type DateTime in sql so you also need to cast this column in date to match the current date like this
cast([SubmmitedDateTime] as Date) = cast(getdate() as date);
So you query will look like this
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE cast([SubmmitedDateTime] as Date) = cast(getdate() as date)";
You are not assigning data source to GridView1. Please use the following code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=AXSQL;Initial Catalog=UniKL;User ID=aten;Password=pass#WORD1";
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";
//GridView1.DataBind();
connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);
//Get data into a reader
SqlDataReader sr = command.ExecuteReader();
//command.ExecuteNonQuery();
//Set the datasource of GridView1
GridView1.DataSource = sr;
GridView1.DataBind();
command.Dispose();
connection.Close();
One suggestion would be to change:
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";
to something like:
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = " + DateTime.Now.toShortDateString();
or
sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = " + DateTime.Now.toString("yyyy-MM-dd");
I'am making a time attendance system and I don't know how to store datetime in database. I really need some help with my system if anyone has any code for time attendance please share your Code a little help would do thanks..
Here is my Code:
con = newSqlConnection(#"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
dt = new DataTable();
cmd = new SqlCommand(#"SELECT EmpID FROM data WHERE EmpID='" + Code.Text + "'", con);
con.Open();
sdr = cmd.ExecuteReader();
int count = 0;
while (sdr.Read())
{
count = count + 1;
}
con.Close();
if (count == 1)
{
con.Open();
DateTime dtn = DateTime.Now;
dtn = Convert.ToDateTime(DateTime.Now.ToString("hh:mm"));
string query = #"INSERT INTO Time (TimeIn) Values ('" + dtn + "')";
cmdd = new SqlCommand(query, con);
sdr = cmdd.ExecuteReader();
sdr.Read();
dataGridView.DataSource = databaseDataSet.Time ;
con.Close();
MessageBox.Show("Verify Ok");
}
else
{
MessageBox.Show("Please Try Again");
}
Do not use ExecuteReader() but ExecuteNonQuery(); add query parameters, do not modify query text, technically it could be something like that:
...
if (count == 1) {
...
DateTime dtn = DateTime.Now;
string query =
#"insert into Time (
TimeIn)
values (
#TimeIn)"; // <- query parameter instead of query text modification
using (var query = new SqlCommand(query, con)) {
// bind query parameter with its actual value
query.Parameters.AddWithValue("#TimeIn", dtn);
// Just execute query, no reader
query.ExecuteNonQuery();
}
...
However, table Time as it appears in the question looks very strange, hardly does it contain TimeIn field only.