Hours sum of columns - c#

I am using this code to save hours but with the use ShowFooter property, can I enter the spaces under the columns in total how to have a use code and summaryitem format what should it be?
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO LogBook (Se,Me)VALUES(,#Se,#Me)", connection);
cmd.Parameters.AddWithValue("#Se", Convert.ToDateTime(textEdit7.Text).ToString("HH:mm"));
cmd.Parameters.AddWithValue("#Me", Convert.ToDateTime(textEdit8.Text).ToString("HH:mm"));
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();

After you are done inserting the data in the database , you can simply use a datareader and achieve your goal :
int totalhours;
SqlCommand cmd = new SqlCommand("Select Se,Me from LogBook",con)
SqlDataReader dr = cmd.ExecuteREader();
While (dr.Read)
{
totalhours = totalhours + Convert.ToInt32(dr[0].ToString().Split(':')(0)) + Convert.ToInt32(dr[1].ToString().Split(':')(0));
}
MessageBox.Show(totalhours);

Related

How can I store SQL Server query value to variable?

I want to sum all values of a column (ttl), and store result in a variable (sum), I tried some code snippets, but I didn't get any success.
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = '"+ textBox1.Text +"'",con);
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
sum = Convert.ToInt32(dr[0]);
MessageBox.Show(sum.ToString());
con.Close();
}
In your code, you should close the connection after the loop, closing the connection inside the loop will cause an error:
while (dr.Read())
{
sum = Convert.ToInt32(dr[0]);
MessageBox.Show(sum.ToString());
}
con.Close();
Sum should return a single value, so you can simply get the value like this:
int sum = Convert.ToInt32(cmd1.ExecuteScalar());
Adding a variable directly to query makes it vulnerable for injections. Use parameters instead:
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = #id",con);
cmd1.Parameters.Add("#id", SqlDbType.VarChar).Value = textBox1.Text;

total of values record from the sql database

I want to return the total of the values in record "hours" on the table "Courses" from my sql database I tried this code but it doesn't work:
SqlCommand cmd = new SqlCommand("Select Courses.hours from Courses inner join Sched on Courses.Id = Sched.SCourses ", con2);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses");
Label3.Text = cmd2.ToString();
}
You are not specified the connection for your sql command cmd2 .
Try this .
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses",con2);
Label3.Text = cmd2.ExexcuteScalar().ToString();
There are two problems in the code: doing while (rdr.Read()) you loop through all rows of result set and execute Select sum(hours)... as many times as many rows you get in the first query.
Depends on requirements, you might want to do if instead of while
if (rdr.Read())
Next, cmd2.ToString(); will not output the result of the query. You should either use ExecuteReader as in the first case, or use ExecuteScalar
if (rdr.Read())
{
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses", con2);
Label3.Text = cmd2.ExecuteScalar().ToString();
}
Why are you totaling your hours using separate queries. Use group by clause and run only once.
SqlCommand cmd = new SqlCommand("Select Courses.id, Sum(Courses.hours) from Courses inner join Sched on Courses.Id = Sched.SCourses group by Course.id")
SqlDataReader rdr = cmd.ExecuteReader();
Label3.Text = cmd.ExecuteScalar().ToString();
Hope it will help.

How to insert date time in database?

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.

Truncate DataGridView fields so it doesnt exceed 10 characters?

So I have a form that when it is opened, loads selected information from a database. However, I want to truncate the Date column, so instead of showing how
'DD/MM/YYYY HH:mm:ss a.m/p.m'
I want it to only show
'DD/MM/YYYY'
I'm using SQL Server Management Studio for my database, and was under the impression that a Date type in that didn't record the time field anyway.
My code for populating the DGV:
SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=FarmersMarket;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cmd.Connection = con;
con.Open();
cmd.CommandText = "Select EventID, EventDate, Location from Events";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
int n = dgvEvents.Rows.Add();
dgvEvents.Rows[n].Cells[0].Value = dr[0].ToString();
dgvEvents.Rows[n].Cells[1].Value = dr[1].ToString();
dgvEvents.Rows[n].Cells[2].Value = dr[2].ToString();
}
}
con.Close();
I think this can be your solution but not a good solution
dgvEvents.Rows[n].Cells[1].Value = dr[1].TrimEnd(' ').ToString();

sum () command not return the added value from table

I want to sum amount value in the income table where a date is been entered from a textbox.
try
{
con.Open();
SqlDataReader myReader = null;
SqlCommand cmd = new SqlCommand("select sum(amount) from income where date='" + TextBox15.Text + "'", con);
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
TextBox16.Text = (myReader["amount"].ToString());
}
con.Close();
}
catch (Exception e1)
{
Label1.Text = e1.Message;
}
My amount data type is decimal
I don't see any reason to use ExecuteReader in your case. Use ExecuteScalar instead which is exactly you need because your query returns only one column with one row.
Executes the query, and returns the first column of the first row in
the result set returned by the query.
And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
For example;
SqlCommand cmd = new SqlCommand("select sum(amount) from income where date = #date", con);
cmd.Parameters.AddWithValue("#date", TextBox15.Text);
TextBox16.Text = cmd.ExecuteScalar().ToString();
First of all user parametrized queries to avoid SQL injection attacks.
There is no column amount in your result, either add alias to your aggregation result or just return first value from reader.
try
{
con.Open();
SqlDataReader myReader = null;
SqlCommand cmd = new SqlCommand("select sum(amount) from income where date = #date", con);
cmd.Parameters.AddWithValue("#date", TextBox15.Text);
myReader = cmd.ExecuteReader();
if (myReader.Read())
{
TextBox16.Text =myReader[0].ToString();
}
con.Close();
}
catch (Exception e1)
{
Label1.Text = e1.Message;
}
Also change while to if because only one result will be returned.
Problem: there is no column amount.
so use alias as below:
Example:
select sum(amount) as totalamount from income where date=#datevalue
=>to avoid sql injection attacks use parameterised queries:
Complete Solution: Change You code as below:
try
{
con.Open();
SqlDataReader myReader = null;
SqlCommand cmd = new SqlCommand("select sum(amount) as totalamount from income where date=#datevalue", con);
cmd.Parameters.Add(new SqlParameter("#datevalue", TextBox15.Text));
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
TextBox16.Text = (myReader["totalamount"].ToString());
}
con.Close();
}
catch (Exception e1)
{
Label1.Text = e1.Message;
}
Why don't you simply do this:
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select isnull(sum(amount),0) from income where date = #date", con);
cmd.Parameters.AddWithValue("#date", TextBox15.Text);
TextBox16.Text = cmd.ExecuteScalar().ToString();
con.Close();
}
catch (Exception e1)
{
Label1.Text = e1.Message;
}
If you can find the time, try giving your objects some reasonable name, quite unlike TextBox16 ...

Categories