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!
Related
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();
}
I have a problem: two days ago, was I face a problem in the history of the introduction of the history of the coordination I've dissolution. But now I want to look in the two periods of time I've attached by typing the code in the image please help when press button search get all data from database
enter image description here
DataTable dt = PFUCommonCLass.Common.GetDataTableModify
(#"SELECT * FROM Tbl_Invoice
WHERE Fld_Date BETWEEN " + txtStartDate.Text + "And" + txtEndDate.Text + "");
)
GridView1.DataBind();
write this query
SELECT * FROM Tbl_Invoice
WHERE Fld_Date BETWEEN #tdate1 and #tdate2;
cmd.parameter.Addwithvalue("#tdate1",txtstartdate.text);
cmd.parameter.Addwithvalue("#tdate12",txtenddate.text);
Please watch this video. this explains it. You can use date picker
Sample code:
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
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);
I want to get data between two dates.I am using a MySql database with my C# winforms. At the time of inserting the dates I converted the date to dd-MM-yyyy and saved these dates in the database having column of type varchar. Now I want to fetch results between two dates here is my code:
string dateFrom = dtp_dfrom.Value.ToString("dd-MM-yyyy");
string dateTo = dtp_dto.Value.ToString("dd-MM-yyyy");
//MessageBox.Show(dateFrom+" "+dateTo);
conn = new MySqlConnection(myconstring);
DataTable dt = new DataTable();
MySqlDataAdapter sda = new MySqlDataAdapter("SELECT trans_date, product_type AS Item, product_quantity, amount, SUM( product_quantity ) AS Qty, SUM( amount ) AS 'Total Price' FROM main_table WHERE trans_date BETWEEN '"+dateFrom+"' AND '"+dateTo+"' GROUP BY product_type", conn);
sda.Fill(dt);
Now the problem is I am not getting the date as required.Anybody can help me out. I am very new to dates formats. Thanks in advance.
I converted the date to dd-MM-yyyy and saved these dates in the
database having column of type varchar
No offense but this is terribly wrong. There is no reason to use varchar as column type for your date values. Use DATE or DATETIME column types instead. That's what they for.
MySQL Data Types
In your case, I suggest you to use DATE column type because it supports YYYY-MM-DD format.
And you should always use parameterized queries. This kind of string manipulations are open for SQL Injection attacks.
string dateFrom = dtp_dfrom.Value.ToString("yyyy-MM-dd");
string dateTo = dtp_dto.Value.ToString("yyyy-MM-dd");
using(MySqlConnection conn = new MySqlConnection(myconstring))
{
DataTable dt = new DataTable();
using(MySqlCommand cmd = new MySqlCommand("SELECT trans_date, product_type AS Item, product_quantity, amount, SUM( product_quantity ) AS Qty, SUM( amount ) AS 'Total Price' FROM main_table WHERE trans_date BETWEEN #dateFrom AND #dateTo GROUP BY product_type"))
{
cmd.Parameters.AddWithValue("#dateFrom", dateFrom);
cmd.Parameters.AddWithValue("#dateTo", dateTo);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd, conn);
sda.Fill(dt);
}
}
You cannot do a between on a varchar column, you have to cast it to datetime/date first.
Like the following:
cast(trans_date as date) BETWEEN '"+dateFrom+"' AND '"+dateTo+"'
Though there is no reason why you are saving a date value into a varchar column, you should modify the table and use the correct columntype so you don't need to cast.
Btw, you should use parameters instead of string manipulations.
You might be looking for STR_TO_DATE
string dateFrom = dtp_dfrom.Value.ToString("yyyy-MM-dd HH:mm:ss");
string dateTo = dtp_dto.Value.ToString("yyyy-MM-dd HH:mm:ss");
MySqlDataAdapter sda = new MySqlDataAdapter("SELECT trans_date, product_type AS Item, product_quantity, amount, SUM( product_quantity ) AS Qty, SUM( amount ) AS 'Total Price' FROM main_table WHERE STR_TO_DATE(trans_date,''%d-%m-%Y'') BETWEEN '"+dateFrom+"' AND '"+dateTo+"' GROUP BY product_type", conn);
You can't use BETWEEN with varchar data, you'll have to use datetime/date as the column type.
It would also be better to use parameters with your query like so:
DataTable dt = new DataTable();
MySqlCommand cmd = new MySqlCommand("SELECT trans_date, product_type AS Item, product_quantity, amount, SUM( product_quantity ) AS Qty, SUM( amount ) AS 'Total Price' FROM main_table WHERE trans_date BETWEEN #from AND #to GROUP BY product_type", conn);
try
{
SqlParameter param;
param = new MySqlParameter("#from", MySqlDbType.DateTime);
param.Value = dateFrom ;
cmd.Parameters.Add(param);
param = new MySqlParameter("#to", MySqlDbType.DateTime);
param.Value = dateTo;
cmd.Parameters.Add(param);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
sda.Fill(dt);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
Try this, but I stored date using DateTime as data type.
SqlConnection con = new SqlConnection("Data Source=xxx\\SQLEXPRESS;Initial Catalog=abc;Integrated Security=true;");
con.Open();
SqlCommand cmd = new SqlCommand("select p.POID,p.SupplierID,p.SupplierDesc, p.CreateDate, p.PaymentDetails,p.Status,q.Quantity,q.BalQty,q.PartNo from PoToSupplierMaster p inner join PoToSupplierMasterItems q on p.POID=q.SNO where q.PartNo='" + DropDownList3.SelectedItem.Text + "' and p.CreateDate between '" + TextBox1.Text + "' and '" + TextBox2.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
in my case I used gridview. but its working fine.
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;
}