How to select data between two date ranges using datepicker c# - c#

Using Visual studio coding C# I have a windows form and have two datetime pickers, how would I select two different date ranges and retrieve data from my SQL database. This is what I have done so far...
SqlConnection ssl = new SqlConnection();
ssl.ConnectionString = #"connection goes ";
ssl.Open();
var a = dateTimePicker1.Value.ToString("yyyy-MM-dd");
var b = dateTimePicker2.Value.ToString("yyyy-MM-dd");
SqlDataAdapter ad = new SqlDataAdapter("SELECT name FROM DATABASENAME WHERE columnname >='" + a + "' AND modified_time <= '"+ b +"'", ssl);
DataTable dt = new DataTable();
ad.Fill(dt);
dataGridView1.DataSource = dt;

When you do this:
"... >= '" + a + "' AND ..."
You're creating a string literal that has your date value in it. The database won't treat it as a date though, and if the query executes it won't do what you want.
Instead, parameterize your query, which is the correct way to pass the dates (or any other values) in:
SqlDataAdapter ad =
new SqlDataAdapter("SELECT name FROM DATABASENAME WHERE columnname >= #Date1 AND modified_time <= #Date2", ssl);
ad.SelectCommand.Parameters.AddWithValue("#Date1", dateTimePicker1.Value);
ad.SelectCommand.Parameters.AddWithValue("#Date2", dateTimePicker2.Value);

Related

date is not compare to database where combobo selected item

I am creating a project that user have to select the date in Combobox but where I have select that date in Combobox that is displaying the error date
String was not recognized as a valid DateTime.'
I am trying to fetch date from database in slq.
Below is my code
System.Data.DataTable dt;
SqlConnection con=new SqlConnection(#"Data Source=krupal;Initial Catalog=LOANNOTICE;Integrated Security=True");
con.Open();
this.cmbmonth.FormatString = "yyyy/ MM/dd";
// DateTime dat = Convert.ToDateTime(cmbmonth.SelectedItem.ToString("yyyy/MM/dd"));
//var date = cmbmonth.Text;
//var d1 = Convert.ToDateTime(cmbmonth.Text);
// MessageBox.Show("" + d1);
string Querie=("SELECT HCODE ,(select top 1 rtrim(Name) From RNSB_TEST.dbo.FC014076 p with(nolock) where convert(varchar,PrdCd) = convert(varchar,HCODE)) as PrdName,count(*) as NoOfAcc,round(Sum(BAL2802),2) as PrintAmt ,round(SUM(IntAmt),2) as TotalInt,0 as TDSAmount, round(SUM(IntAmt),2) as NetIntAmt, round((Sum(BAL2802) + SUM(IntAmt)),2)as TotalAmt from LOANNOTICE.dbo.UNCLAIM_DEPO with(nolock) where EffeDate='"+Convert.ToDateTime(cmbmonth.SelectedText).ToString("yyyy/MM/dd") + "' group by HCODE union SELECT HCODE, (select top 1 rtrim(Name) From RNSB_TEST.dbo.FC014076 p with(nolock) where convert(varchar, PrdCd) = convert(varchar, HCODE)) as PrdName,count(*) as NoOfAcc,round(Sum(MatAmt), 2) as PrintAmt ,round(SUM(IntAmt), 2) as TotalInt,round(sum(TDS_Amount), 2) as TDSAmount, round(SUM(Net_Int), 2) as NetIntAmt, round((Sum(MatAmt) + SUM(Net_Int)), 2) as TotalAmt from LOANNOTICE.dbo.UNCLAIM_DEPO_TDR with(nolock) where EffeDate = '"+Convert.ToDateTime(cmbmonth.SelectedText).ToString("yyyy/MM/dd") + "' group by HCODE");
SqlCommand cmd = new SqlCommand(Querie, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
dt = new System.Data.DataTable();
sda.Fill(dt);
Anyone have a solution please let me know fast.
Thanks.
You need to parse string into valid date time.
Your conversion was wrong, please convert string to date time and then pass to appropriate date fields.
please refer this link .
It draws my attention that you have this blank space here:
this.cmbmonth.FormatString = "yyyy/ MM/dd"
Anyway, you should always check dates passed as string, and throw an exception if you can't cast them:
if (!DateTime.TryParse(_date, out DateTime date))
{
throw new InvalidCastException("Not a valid date.");
}
And last, try to set you SqlCommand parameters this way, is more readable and you don't have to deal with string interpolation (checkout for:
using (DbConnection connection = new SqlConnection("MyConnectionString"))
{
using (DbCommand command = new SqlCommand(connection))
{
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM MyTable WHERE Date = #Date";
command.Parameters.Add("#Date", SqlDbType.Date);
command.Parameters["#Date"].Value = date;
}
}
Give it a try! :)
Regards!

Show record after comparing dates stored as varchar in Database

I have dates stored in the database as dd/mm/yy, I want to show records based on dates. I have wrote following code but it is not returning correct results. I think there is some mistake in query.
private void FillDataGrid()
{
con.Open();
var date1 = Convert.ToDateTime(datePicker1.SelectedDate.Value).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var date2 = Convert.ToDateTime(datePicker2.SelectedDate.Value).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
label4.Content = date1;
label5.Content = date2;
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id, product_name, quantity, left_qty, purchaseDate, manufacturing_date, expiryDate from batch where Convert(varchar, expiryDate, 103) BETWEEN '" + date1 + "' AND '" + date2 + "' ", con);
DataSet ds = new DataSet();
DataTable dt = new DataTable(); // being used to calculate total price
sda.Fill(dt);
sda.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
// Binding the Grid with the Itemsource property
dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
}
con.Close();
}
It is giving wrong results snap is attached Image of Wrong Results
Take this line:
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id,product_name,quantity,left_qty,purchaseDate,manufacturing_date,expiryDate from batch where Convert(varchar,expiryDate,103) BETWEEN '" + date1 + "' AND '" + date2 + "' ", con);
...and turn it into something more like this:
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id,product_name,quantity,left_qty,purchaseDate,manufacturing_date,expiryDate from batch where Convert(varchar,expiryDate,103) BETWEEN #from AND #to;", con);
sda.SelectCommand.Parameters.AddWthValue("#from", "'" + Convert.ToDateTime(datePicker1.SelectedDate.Value).ToString("yyyyMMdd") + "'");
sda.SelectCommand.Parameters.AddWthValue("#to", "'" + Convert.ToDateTime(datePicker2.SelectedDate.Value).ToString("yyyyMMdd") + "'");
So I quickly spoofed this up on a SQL Sever 2016 database with a Visual Studio 2017 solution. I had to remove the single quotes to get it to work, which I had an inkling might be the case. This is the code I actually ended up getting working:
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id, product_name, quantity, left_qty, purchaseDate, manufacturing_date, expiryDate from batch where CONVERT(DATE, expiryDate, 103) BETWEEN #from AND #to;", con);
sda.SelectCommand.Parameters.AddWithValue("#from", Convert.ToDateTime(datePicker1.Value).ToString("yyyyMMdd"));
sda.SelectCommand.Parameters.AddWithValue("#to", Convert.ToDateTime(datePicker2.Value).ToString("yyyyMMdd"));
Note that my date time pickers didn't work with SelectedDate but you might well be targeting a different version of .NET, etc. so maybe you will need those. Anyway, the key here is:
CONVERT your text string to a DATE using 103 to make it handle the dd/mm/yyyy format;
parameterise your from and to dates to avoid SQL injection, etc.;
Don't add the single quotes ' as this is all handled nicely for you when you use parameters.
I agree with the other commenters above though; storing dates as text in a database is a disaster waiting to happen. This should get you going for the short-term, but I would recommend taking a step back and thinking about this in a longer term scenario.
Finally, here's an image of it working, and the code behind:
I have solved it with help of #Richard Hansel. And now below is working line of Code.
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id,p_name,quantity,left_qty,purchaseDate,manufacturing_date,expiryDate from batch b cross apply (select p_name from products p where p.p_id_pk = b.product_id_fk) products where Convert(DATE,expiryDate,103) BETWEEN #from AND #to", con);
sda.SelectCommand.Parameters.AddWithValue("#from", Convert.ToDateTime(datePicker1.SelectedDate.Value).ToString("yyyyMMdd"));
sda.SelectCommand.Parameters.AddWithValue("#to", Convert.ToDateTime(datePicker2.SelectedDate.Value).ToString("yyyyMMdd"));
Try using delimiter (#) like below on query.
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id,product_name,quantity,left_qty,purchaseDate,manufacturing_date,expiryDate from batch where Convert(varchar,expiryDate,103) BETWEEN #" + date1 + "# AND #" + date2 + "# ", con);

delete fields from sql database where the date is a previous date to today in c#

SqlConnection sqlcon = new SqlConnection(GlobalClass.DBLocate);
sqlcon.Open();
string query = "Delete from [Plans] Where Date < '" +
GlobalClass.Date.ToShortDateString() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
sda.SelectCommand.ExecuteNonQuery();
I have tried many techniques but everything in this database is deleted or nothing at all.
Many thanks
Instead of passing in the date as a string, why don't you write the SQL using it's native date functions?
As this question is tagged as C# and not with any specific flavor of SQL, I am writing this connecting to SQL Server.
You also did not provide the DDL for the table that is being deleted from. The code is based on using a proper column type for the [Date] column, which would be some variant of DateTime.
The following statement should delete everything up the current DateTime
string query = "DELETE from [Plans] WHERE Date < GetDate()";
If you need to fine tune this to everything before today, then you can use CAST/CONVERT and just get the Date portion:
string query = "DELETE from [Plans] WHERE Date < Cast(GetDate() as Date)";
You also don't need to use a DataAdapter for a NonQuery; it's return type is an int, and can be assinged directly
int RowsDeleted = cmd.ExecuteNonQuery();
So putting it all together, we get this code block. I also wrapped within a using block so that the resources are properly cleaned up afterwards.
int RowsDeleted = -1;
using (SqlConnection sqlcon = new SqlConnection(GlobalClass.DBLocate)) {
string query = "DELETE from [Plans] WHERE Date < GetDate()";
SqlCommand cmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
RowsDeleted = cmd.ExecuteNonQuery();
sqlcon.Close();
}
Try this. I guess your date value is to new, and hence deletes everything.
SqlConnection sqlcon = new SqlConnection(GlobalClass.DBLocate);
sqlcon.Open();
DateTime yesterday = DateTime.Today.AddDays(-1);
string query = "Delete from [Plans] Where Date <= '" +
yesterday.ToShortDateString() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
sda.SelectCommand.ExecuteNonQuery();

Display data in 2 tables in one crytal report in c#

I am trying to display some data on crystal report. after written the code the issued part of the report displayed well while the receiving part displayed only the first data within the range selected and duplicated several times. here is the code below
public DataSet itembincardreport(string date1, string date2, string
itemcode)
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = null;
Connection cs = new Connection();
con = new SqlConnection(cs.DBcon);
con.Open();
DataSet ds = new DataSet();
frmReport frm = new frmReport();
string sql = "select * from ISSUED, RECEIVED WHERE
ISSUED.ITEMCODE=RECEIVED.ITEMCODE AND ISSUED.ITEMCODE = '" + itemcode + "'
AND RECEIVED.ITEMCODE = '" + itemcode + "' and ISSUED.TRANSDATE
between '" + Convert.ToDateTime(date1) + "' and '" +
Convert.ToDateTime(date2) + "' and RECEIVED.TRANSDATE between '" +
Convert.ToDateTime(date1) + "' and '" + Convert.ToDateTime(date2) + "'";
SqlDataAdapter dadbt = new SqlDataAdapter(sql, mycon.DBcon);
dadbt.Fill(ds);
dadbt.Dispose();
return ds;
}
The root cause of your problem is the query. Whether the received and issued tables have multiple rows that match each other or not, I cannot say (you need to post some better example table data than the screenshot given) but your query in the string should be written like this:
string sql =
#"select *
from
ISSUED
inner join
RECEIVED
on
ISSUED.ITEMCODE=RECEIVED.ITEMCODE -- this is probably the fault
-- try joining on ISSUEDID = RECEIVED instead??
where
ISSUED.ITEMCODE = #itemcode and
ISSUED.TRANSDATE between #date1 and #date2 and
RECEIVED.TRANSDATE between #date1 and #date2";
Later in your code, you should call:
var c = new SqlCommand();
c.CommandText = sql;
c.Connection mycon;
c.Parameters.AddWithValue("#itemcode", itemcode);
c.Parameters.AddWithValue("#date1", Convert.ToDateTime(date1)); //you should make the method argument a DateTime
c.Parameters.AddWithValue("#date2", Convert.ToDateTime(date2)); //you should make the method argument a DateTime
SqlDataAdapter dadbt = new SqlDataAdapter(c);
That's how to PROPERLY do database queries with parameters.. Now whether there are duplicate rows or not is purely down to your table data*, but at least your SQL is immune from hackers putting an itemcode of '; DROP table issued; -- in and screwing up your world
*post some detailed example data if you want help with that and I'll edit this answer. Take a look at SQLFiddle.com

Get the string data from database and convert it into date object in the query

I am developing an ATM software in which I want to get report by entering the start date and end date. The date is saving in my table is in the form of string dd/MM/yyyy. I am trying the following code and getting the exception of incorrect syntax.
public DataTable getReportByDate(DateTime startDate, DateTime endDate)
{
try
{
DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from [Transaction] Where CAST(CurrDate AS Date) >=" + startDate + " AND CAST(CurrDate AS Date) <=" + endDate + ";", connectionString);
// Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
}
return table;
}
catch (Exception e)
{
return null;
}
}
Please help me.
Regards
Ok, first off, DO NOT turn the exception into a return null
catch(Exception e)
{
return null;
}
It is bad practice as you suck up EVERY possible exception.
Instead you should only catch the exceptions which the sql adapter is supposed to throw, or even better: do not catch them, instead document them and catch them further outward, because if something goes wrong in this method it means your SQL connection or your code is broken.
If you leave it as is you only hide problems and make debugging much harder.
Secondly, you should use parameters in your query.
Now to the syntax error: startDate and endDate are of type DateTime, so you should convert them to a string first with .ToString("dd/MM/yyyy") - this would be less of a hassle with parameters.
Change
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from [Transaction] Where CAST(CurrDate AS Date) >=" + startDate + " AND CAST(CurrDate AS Date) <=" + endDate + ";", connectionString);
To
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from [Transaction] Where CAST(CurrDate AS Date) >='" + startDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND CAST(CurrDate AS Date) <='" + endDate.ToString("yyyy-MM-dd HH:mm:ss") + "';", connectionString);
UPDATE:
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from [Transaction] Where CAST(CurrDate AS Date) >='" + startDate.ToString("dd/MM/yyyy") + "' AND CAST(CurrDate AS Date) <='" + endDate.ToString("dd/MM/yyyy") + "';", connectionString);
You should definitely use parameters in your query - both to avoid SQL injection attacks, as well as improve performance (through execution plan reuse). No one so far has showed it - so here it is:
public DataTable getReportByDate(DateTime startDate, DateTime endDate)
{
DataTable table = new DataTable();
string sqlStmt =
"SELECT * FROM [dbo].[Transaction] " +
"WHERE CAST(CurrDate AS DATE) >= #startDate " +
"AND CAST(CurrDate AS DATE) <= #endDate";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(sqlStmt, connection))
{
cmd.Parameters.Add("#startDate", SqlDbType.Date).Value = startDate.Date;
cmd.Parameters.Add("#endDate", SqlDbType.Date).Value = endDate.Date;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
}
return table;
}
}
I did try, the sql works normally in a query editor, however, it appears it can only work if parameterized.
So I'm reposting the code, I noticed a moderator converted my initial response to comment.
public DataTable getReportByDate(DateTime startDate, DateTime endDate)
{
DataTable table = new DataTable();
string query = "select * from [transaction] where cast(currdate as date) >= #startdate and cast(currdate as date) <= #enddate";
using (SqlConnection connection = new SqlConnection("server=(local);database=quicksilver;integrated security=true"))
{
connection.Open();
SqlCommand command = new SqlCommand(query);
command.Parameters.AddWithValue("#startdate", startdate);
command.Parameters.AddWithValue("#enddate", enddate);
command.Connection = connection;
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
//
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(table);
}
return table;
}

Categories