I am trying to sort my database data in datagridview using DateTimePicker control , the type of date column in my Event_test table is datetime2
SqlDataAdapter sda = new SqlDataAdapter("SELECT * from Event_test where date between '"
+dateTimePicker1.Value.ToString()+"' AND'"+dateTimePicker2.Value.ToString()+ "'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
This solution doesn't work properly , it sorts data wrongly at first time and when i change time pickers this error occurs :
Conversion failed when converting date and/or time from character
string
Any help is appreciated.
So how shall I adjust the select statement to get what I need?
Looks like dateTimePicker1 and dateTimePicker2
are both unchangeable ; they are set to 01/10/2016 and 10/10/2016 and whenever i change dates it shows me results between those dates !!
You really need to format your date string to match the format of SQL-Server:
string sqlFormat = "yyyy-MM-dd HH:mm:ss.fff";
String query = "SELECT * from Event_test where date between '"
+ dateTimePicker1.Value.ToString(sqlFormat) + "' AND'"
+ dateTimePicker2.Value.ToString(sqlFormat) + "'";
Better option is to use Sql Parameters (try to avoid query strings concatenation):
var sda = new SqlDataAdapter("SELECT * from Event_test where [date] between #p1 AND #p2", con);
SqlParameter dateParamFrom = new SqlParameter("#p1", SqlDbType.DateTime2);
dateParamFrom.Value = dateTimePicker1.Value;
SqlParameter dateParamTo = new SqlParameter("#p2", SqlDbType.DateTime2);
dateParamTo.Value = dateTimePicker2.Value;
sda.SelectCommand.Parameters.Add(dateParamFrom);
sda.SelectCommand.Parameters.Add(dateParamTo);
Related
Code:
private void button2_Click(object sender, System.EventArgs e)
{
OleDbDataAdapter dbc = new OleDbDataAdapter("SELECT ReceiptID,ID,Name,Paid,Due FROM lastpays where [Dateofpayment] >= "+ dateTimePicker1.Value.Date + " AND [Dateofpayment] < " + dateTimePicker2.Value.Date + "", con);
DataTable data = new DataTable();
dbc.Fill(data);
dataGridView1.DataSource = data;
}
Error:
System.Data.OleDb.OleDbException: 'Syntax error (missing operator) in
query expression '[Dateofpayment] >= 11-01-2020 12:00:00 AM AND
[Dateofpayment] < 11-01-2020 12:00:00 AM'.'
MS Access (JET Red) requires date literals in SQL to be in the form #MM/dd/yyyy#.
Your code however inserts the default string representation of a DateTime value using CurrentCulture, without using any delimiters.
Because you're directly concatenating String values with DateTime values, which invokes DateTime.ToString() which is CurrentCulture-sensitive.
Use parameters to avoid this issue entirely, and to prevent SQL injection.
Also, you're using the same dateTimePicker instance for both values - I think you mean to use dateTimePicker1 and dateTimePicker2 - though you should rename them to minDatePicker and maxDatePicker to be clear what their purpose is.
const String sql = #"SELECT ReceiptID,ID,Name,Paid,Due FROM lastpays where [Dateofpayment] >= ? AND [Dateofpayment] < ?";
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandText = sql;
OleDbParameter pFrom = cmd.CreateParameter();
pFrom.OleDbType = OleDbType.Date;
pFrom.Value = dateTimePicker1.Value.Date;
cmd.Parameters.Add( pFrom );
OleDbParameter pTo = cmd.CreateParameter();
pTo.OleDbType = OleDbType.Date;
pTo.Value = dateTimePicker2.Value.Date;
cmd.Parameters.Add( pTo );
OleDbDataAdapter da = new OleDbDataAdapter( selectCommand: cmd );
DataTable data = new DataTable();
da.Fill( data );
dataGridView1.DataSource = data;
Even though parameters are preferred, the questioneer deserves an answer why the code is failing.
The date values must be converted to valid string expressions:
OleDbDataAdapter dbc = new OleDbDataAdapter("SELECT ReceiptID,ID,Name,Paid,Due FROM lastpays where [Dateofpayment] >= #"+ dateTimePicker1.Value.Date.ToString("yyyy'/'MM'/'dd") + "# AND [Dateofpayment] < #" + dateTimePicker2.Value.Date.ToString("yyyy'/'MM'/'dd") + "#", con);
I have a column in my database that holds a string on different week days for my contact.
For Example: Contact 1 works Monday and Wednesday.
So in the Week_Day column the string for Contact 1 is "Monday, Wednesday". I am trying to only show the rows who work on the current day of the week, the code is below. I tried using the IN clause, but it's not working because I don't have a set day of the week I want to filter. HELP!
string today = DateTime.Today.ToString("MM-dd-yy");
string day = DateTime.Today.DayOfWeek.ToString();
string find = "select convert(varchar(8), start, 10) AS start, convert(varchar(8), end_date, 10) AS end_date, ContactName, DepartmentName, Hours, Phone, Week_Day from Schedule join Contacts on Schedule.ContactId = Contacts.ContactId inner join Departments on Contacts.DepartmentId = Departments.DepartmentId where #Current BETWEEN start AND end_date AND Week_Day IN (#Day)";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#Current", SqlDbType.Date).Value = today;
comm.Parameters.Add("#Day", SqlDbType.NVarChar).Value = day;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds);
GridView3.DataSource = ds;
GridView3.DataBind();
con.Close();
Well you can get the current day of week (name) like so:
string day = DateTime.Today.ToString("dddd");
Then you can use that in your WHERE query with a LIKE. Change your query to have:
WHERE Week_Day LIKE #day
And add you param for #day to include % at start and end:
comm.Parameters.Add("#Day", SqlDbType.NVarChar).Value = "%" + day + "%";
More info on LIKE here
NOTE: As some comments have already mentioned it would be better to not store the data this way in a single string column, but I have answered based on your question as it stands.
Perhaps with DateName() and CharIndex()
Where CHARINDEX(DateName(WEEKDAY,GetDate()),Week_Day)>0 and...
I have two columns with date_of_delivery and date_of_receipt. I want to filter my data
private void button25_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
if(radioButton9.Checked)
{
if ((Convert.ToDateTime(dateTimePicker3.Value)) <= (Convert.ToDateTime(dateTimePicker4.Value)))
{
try
{
string query = "SELECT work_id, surname, first_name, patronymic, type_of_service.name_type_of_service, date_of_receipt, date_of_delivery, car_model.name_model, price_for_work FROM mechanic INNER JOIN work ON work.mechanic_id = mechanic.mechanic_id INNER JOIN type_of_service ON work.type_of_service_id = type_of_service.type_of_service_id INNER JOIN car ON work.car_id = car.car_id INNER JOIN car_model ON car.car_model_id = car_model.car_model_id WHERE work.date_of_receipt >= '" + Convert.ToDateTime(dateTimePicker3.Value) + "' AND work.date_of_delivery <= '" + Convert.ToDateTime(dateTimePicker4.Value) + "'";
MessageBox.Show("" + query);
dataGridView2.DataSource = query;
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.Fill(ds, query);
dataGridView2.DataSource = ds.Tables[query];
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
}
}
else
{
MessageBox.Show("Дата начала ремонта не может быть позже его завершения ");
}
}
else if(radioButton10.Checked)
{
string query = "SELECT work_id, surname, first_name, patronymic, type_of_service.name_type_of_service, date_of_receipt, date_of_delivery, car_model.name_model, price_for_work FROM mechanic INNER JOIN work ON work.mechanic_id = mechanic.mechanic_id INNER JOIN type_of_service ON work.type_of_service_id = type_of_service.type_of_service_id INNER JOIN car ON work.car_id = car.car_id INNER JOIN car_model ON car.car_model_id = car_model.car_model_id WHERE work.price_for_work BETWEEN " + Convert.ToInt32(textBox16.Text) + " AND " + Convert.ToInt32(textBox17.Text) + "";
MessageBox.Show("" + query);
dataGridView2.DataSource = query;
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.Fill(ds, query);
dataGridView2.DataSource = ds.Tables[query];
}
}
However, the data is not sorted. Because the database format of the date 01.02.2015 . How to make sure everything works
As I wrote in the comments, date types does not have a format.
You are sending a string that represents a date value to the database, (the default .ToString() of the DateTime object is called since there is an implicit conversion from date to string when you are concatenating the DateTime to the sql string).
When using strings for a date value in sql it's best to use ANSI-SQL format which is yyyy-MM-dd. This format guarantees that SQL Server will interpret the string as a proper date.
However, concatenating strings to create an SQL statement is a security hazard, since it's an opening for SQL injection attacks.
The proper way is to use parameterized queries or stored procedures.
Replace your query's where clause from this
WHERE work.date_of_receipt >= '" + Convert.ToDateTime(dateTimePicker3.Value) +
"' AND work.date_of_delivery <= '" + Convert.ToDateTime(dateTimePicker4.Value) + "'"
to this:
WHERE work.date_of_receipt >= #date_of_receipt
AND work.date_of_delivery <= #date_of_delivery
Then use the SqlDataAdapter's SelectCommand's Parameters collection to add the values for the parameters:
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.SelectCommand.Parameters.Add("#date_of_receipt ", SqlDbType.Date).Value = dateTimePicker3.Value;
da.SelectCommand.Parameters.Add("#date_of_delivery", SqlDbType.Date).Value = dateTimePicker4.Value;
(Note that the add command returns a reference to the SqlParameter you've just added, therefor you can write the .Value to specify the value of the parameter when adding it to the SelectCommand.
Note that the value of the DateTimePicker is already a DateTime type, so there is no need to use Convert.ToDateTime when adding it.
Do the same thing with all other queries (of course, don't forget to use the proper data types for the parameters).
System.DateTime dt16 = System.DateTime.Parse(textBox16.Text);
string sTextBox16 = dt16.ToString("dd.MM.yyyy");
System.DateTime dt17 = System.DateTime.Parse(textBox17.Text);
string sTextBox17 = dt17.ToString("dd.MM.yyyy");
string query = "SELECT Required Columns WHERE work.date_of_receipt >= "+sTextBox16 +"' AND work.date_of_delivery <= '" + sTextBox17 +"'";
I have the following code :
Connection c = new Connection();
string select1 =
#"SELECT
E.employeeNumber AS 'Employee Number',
E.employeePrivateName + ' ' + E.employeeFamilyName AS 'Employee Name',
DATEDIFF (MONTH, E.startWorkingDate, GETDATE()) AS 'Seniority in Month',
M.machineName AS 'Machine Name', J.jobName AS 'Job Name',
COUNT(E.employeeNumber) AS 'Number of Times on Machine in Specif Job',
SUM(Number_Of_Days_During_The_Period) AS 'Total Working Days on Machine in Specif Job',
SUM(Salary_per_Period) AS 'The Salary For working on Machine in Specif Job'
FROM
TblEmployee E
INNER JOIN
AllSchedules A_S on E.employeeNumber = A_S.employeeNumber
INNER JOIN
TblJob J on J.jobNumber = A_S.jobNumber
INNER JOIN
TblMachine M on M.machineNumber = A_S.machineNumber
INNER JOIN
TblPeriod P on P.Number = A_S.periodNumber
WHERE
Month(P.fromDate) = Month(#Month)
GROUP BY
E.employeeNumber, E.employeePrivateName, E.employeeFamilyName,
E.startWorkingDate, M.machineName, J.jobName
ORDER BY
E.employeeFamilyName , E.employeePrivateName";
SqlCommand cmd = new SqlCommand(select1, c.con);
DateTime month = comboBox1.Text;
cmd.Connection = c.con;
cmd.Parameters.AddWithValue("#Month", month);
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
I want to run the query, however I need to define a datetime value so it would be a search parameter for the query. How do I save the DateTime variable so that it will hold a month number (10 for october, etc.)
Thanks
In your query you have this line for the WHERE condition
WHERE Month(P.fromDate)= Month(#Month)
THe MONTH function of T-SQL expects to receive a Date for its parameter, so you probably need only
DateTime dt = new DateTime(DateTime.Today.Year, month, 1);
and pass this value for the parameter #Month
cmd.Parameters.AddWithValue("#Month", dt);
EDIT: If you have a combobox with items filled with the month names ordered: (January, February....)
// In array the indexes start at zero.....
if(cboMonths.SelectedIndex >= 0)
{
int month = cboMonts.SelectedIndex + 1;
}
You can use
string monthString = DateTime.ParseExact(comboBox1.Text, "MMMM", CultureInfo.CurrentCulture ).Month.ToString("MM");
and to convert it to an integer:
int month = int.Parse(monthString);
string sMonth = DateTime.Now.ToString("MM");
Given that the SQL Month function returns an integer (Source) you need to replace:
"... WHERE Month(P.fromDate)= Month(#Month) GROUP BY ..."
by
"... WHERE Month(P.fromDate) = " + intMonth.ToString() + " GROUP BY ..."
where intMonth is the integer value of the month selected from your combobox.
However, you will need to make sure that it is just an integer and can't be used as an injection attack. You would be better off putting all your SQL into a stored procedure and passing the month as an integer parameter.
I have two datepickers whose dates are to be used in this query:
da = new SqlDataAdapter(#"
select * from TotalBill
where SaudaDate between
convert(datetime,'" + dtpForDate.Value.Date.ToString("MM/dd/yyyy") + "')
and convert(datetime,'" + dtpToDate.Value.Date.ToString("MM/dd/yyyy") + "')"
, con);
DataSet ds = new DataSet();
da.Fill(ds);
gvDailyBill.DataSource = ds.Tables[0];
When I want to query for one day, I cannot set both datepickers to the same day, but I have to set the From to the day I want and the To to a day beyond. If I don't, the query becomes something like this:
select * from totalbill where SaudaDate between '1/2/2013' and '1/2/2013'
Which of course returns 0 rows. How do I alter my code or query to allow the selection of the same day in the datepickers?
Important first :
You need parametrized query.
var fromDate = dtpForDate.Value.Date;
var toDate = dtpToDate.Value.Date;
string selectSQL = "select * from TotalBill where SaudaDate between #start and #end";
da = new SqlDataAdapter();
SqlCommand selectCMD = new SqlCommand(selectSQL, con);
da.SelectCommand = selectCMD;
selectCMD.Parameters.Add("#start ", SqlDbType.DateTime).Value = fromDate;
selectCMD.Parameters.Add("#end", SqlDbType.DateTime).Value = toDate;
DataSet ds = new DataSet();
da.Fill(ds);
gvDailyBill.DataSource = ds.Tables[0];
Secondly, you filter by date. But when your start date is equal to your end date, you want the datas of all the day.
What if the start date and the end date are different ? Do you want to include all the values of the end date too?
When you say "01/01/2010" to Sql, it understand "01/01/2010 00:00:00". You can't filter by date, but you filter by date*time*. This is an important difference.
So in your case, the right query is I think :
var fromDate = dtpForDate.Value.Date;
var toDate = dtpToDate.Value.Date.AddDays(1); // trick, add one day
In this case, when fromDate == toDate == '1/2/2013', you will get all the datas between '1/2/2013 00:00:00' and '1/3/2013' 00:00:00'. In pure english, you will get all the datas of the day 1/2/2013.
your Query must be like below...
"select * from TotalBill
where CONVERT(VARCHAR(10), SaudaDate, 101) between
convert(datetime,'" + dtpForDate.Value.Date.ToString("MM/dd/yyyy") + "')
and convert(datetime,'" + dtpToDate.Value.Date.ToString("MM/dd/yyyy") + "')"
SaudaDate is in Date time format.... So it may be like this '1/2/2013 07:54:00'
and if you convert this like CONVERT(VARCHAR(10), SaudaDate, 101) then it will become '1/2/2013 00:00:00'
Now it will give you the result you needed..
Try it...
If you wish to include the dates then dont use between. Use greater/less than or equal.
select * from totalbill where SaudaDate >= '2013-02-01' and SaudaDate <= '2013-02-01'
Edit. If your date column is actually a datetime which has times other than 00:00:00.000 then you will need to use the "Like" in your where for a single date.
select * from totalbill where SaudaDate like '2013-02-01%'
Or you will need to add a single day to the second date programatically.
select * from totalbill where SaudaDate >= '2013-02-01' and SaudaDate <= '2013-02-02'
You need to convert SaudaDate to only date part.
Try following:
try
{
da = new SqlDataAdapter(#"
select * from TotalBill
where Cast(Convert(varchar(20),SaudaDate,101) as Datetime) between
convert(datetime,'" + dtpForDate.Value.Date.ToString("MM/dd/yyyy") + "')
and convert(datetime,'" + dtpToDate.Value.Date.ToString("MM/dd/yyyy") + "')"
, con);
DataSet ds = new DataSet();
da.Fill(ds);
gvDailyBill.DataSource = ds.Tables[0];
}
catch (Exception ex){}
This code will work for the same day selection too.
Not tested,
You need to change your SQL query
select * from TotalBill
where SaudaDate >=#yourDateFrom
AND SaudaDate<=#yourDateTo