Conversion failed when converting datetime from character string ASP.NET - asp.net

I get a Conversion failed error when converting DateTime from character string, any help?
sqlcon.Open();
sqlcmd = new SqlCommand("select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] from emp where MyDate between '" + TextBoxData1 + "' and '" + TextBoxData2 + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
GridViewRodyti.DataSource = dt;
GridViewRodyti.DataBind();
sqlcon.Close();

This has got SQL Injection written all over it...
Use parameterized queries e.g.
var sqlCmd = new SqlCommand("select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] from emp where MyDate between '#startDate' and '#endDate'", sqlcon);
sqlCmd.Parameters.Add(new SqlParameter("#startDate", DateTime.Parse(TextBoxData1)));
sqlCmd.Parameters.Add(new SqlParameter("#endDate", DateTime.Parse(TextBoxData2)));
Your issue is probably due to an invalid date format, if you use SqlParameter and convert the string to a DateTime it should take care of the conversion for you.

I would advise you do it like this...
sqlcon.Open();
DateTime date1;
DateTime date2;
DateTime.TryParse(TextBoxData1.Text, out date1); //is TextBoxData1 a TextBox?
DateTime.TryParse(TextBoxData2.Text, out date2);
if (date1 != null && date2 != null) {
sqlcmd = new SqlCommand(
"select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] " +
"from emp where MyDate between #dt1 and #dt2 ", sqlcon);
sqlcmd.Parameters.AddWithValue("#dt1", date1);
sqlcmd.Parameters.AddWithValue("#dt2", date2);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
GridViewRodyti.DataSource = dt;
GridViewRodyti.DataBind();
sqlcon.Close();
}
Using parameterised queries is much nicer and doesn't run the risk of injection.
I have assumed you are using SQLServer.

Related

How to store a select query result ( one result ) to a variable using executescalar() ? ( ASP.NET )

i have to store a select query result in a variable .i'm new in asp.net . i used executescalar but it doesn't work. i try many times but i failed here my last try :
using (SqlConnection sqlConnection = new SqlConnection())
{
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
sqlConnection.ConnectionString = connetionString;
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlConnection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
string result = dataset.Tables[0].ToString();
}
Can you fix the code to me? i have to store the result in a variable
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
string result = null;
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
result = cmd.ExecuteScalar().ToString();
}

Error: An expression of non-boolean type specified in a context where a condition is expected

I want to pass three query string variables, which ars DateFrom, DateTo and UserName. When I call that the variable, it shows an error:
'An expression of non-boolean type specified in a context where a condition is expected, near 'admin'.'".
How can I resolve the issue? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
strDate = Convert.ToDateTime(Request.QueryString["DateFrom"]);
endDate = Convert.ToDateTime(Request.QueryString["DateTo"]);
UserName = Convert.ToSingle(Request.QueryString["UsName"]);
string UserName = Request.QueryString["UsrName"];
string sql;
sql = ("SELECT * FROM tblReport WHERE Date between'" + strDate + "'and'" + endDate + "'and'" + UserName + "'");
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
DataSet dst = new DataSet();
sda.Fill(dst, "tblReport");
crypt.Load(#"D:\My Project\Asp.Net\ITApplication\ITApplication\CrystalReport.rpt");
crypt.SetDataSource(dst);
CrystalReportViewer1.ReportSource = crypt;
}
you are missing something in your where clause... should be like this:
WHERE Date BETWEEN '<FromDate>' AND '<ToDate>'
AND UserName = '<UserName>'
Your SQL string is not formatted well.
Put spaces near yout and operators and use () in your between:
sql = ("SELECT * FROM tblReport WHERE [Date] between ('" + strDate + "' and '" + endDate + "') and UserName='" + UserName + "'");
Side note:
Using SQL strings with concatenating values like this is a very bad idea. It exposes you to SQL Injections, and overall a bad practice. Please consider using Command.Parameters:
SqlCommand Command = new SqlCommand("SELECT * FROM tblReport WHERE [Date] between (#strDate and #endDate) and UserName=#UserName");
Command.Parameters.Add(new SqlParameter("strDate", strDate));
Command.Parameters.Add(new SqlParameter("endDate", endDate));
Command.Parameters.Add(new SqlParameter("UserName", UserName));

Conversion failed

I want to add some parameter to a table and I get this error in the Visual Studio 2013. I'm having trouble with Date & Time. My date & time datatypes used in SQL Server 2008 R2 are Date and Time(7). I get this error
Conversion failed when converting date and/or time from character string
What is my mistake?
My code:
string strquery = "select count(*) from SaloonGeneralReservation where SaloonReservationDate=#SaloonReservationDate";
SqlConnection connection2 = DBConnection.getConnection();
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection2;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#SaloonReservationDate", txt1_date.Text);
int intRowCount = (int) cmd2.ExecuteScalar();
txt1_date.Text = intRowCount.ToString();
connection2.Close();
if (intRowCount == 1)
{
Messages myMsg = new Messages(); // ایجاد نمونه از کلاس
myMsg.CreateMessageAlert("سالن در این تاریخ رزرو شده است . لطفا تاریخ دیگری وارد نمایید.");
txt1_date.Text = "";
}
else
{
string strQuery = "INSERT INTO [WeedingSalonGeneralRes](Date,Time,Fruit,Drink,Desert,MainFood,Salad,TableFlower,SaloonLighting,Saloondesign,SloonCrew,Pastry,GiftCard,customer_id)" + "VALUES(#Date,#Time,#Fruit,#Drink,#Desert,#MainFood,#Salad,#TableFlower,#SaloonLighting,#Saloondesign,#SloonCrew,#Pastry,#GiftCard,#customer_id)";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = strQuery;
string cis = Session["customerID"].ToString();
cmd.Parameters.Add("#Date", txt1_date.Text);
cmd.Parameters.Add("#Time", txt2_time.Text);
cmd.Parameters.Add("#Fruit", fruit);
cmd.Parameters.Add("#Drink", drink);
cmd.Parameters.Add("#Desert", desert);
cmd.Parameters.Add("#MainFood", mainfood);
cmd.Parameters.Add("#Salad", salad);
cmd.Parameters.Add("#TableFlower", tableflower);
cmd.Parameters.Add("#SaloonLighting", saloonlighting);
cmd.Parameters.Add("#Saloondesign", saloondesing);
cmd.Parameters.Add("#SloonCrew", salooncrew);
cmd.Parameters.Add("#Pastry", pastry);
cmd.Parameters.Add("#GiftCard", giftcard);
cmd.Parameters.Add("#customer_id", cis);
cmd.ExecuteNonQuery();
connection.Close();
Response.Redirect("ReservationSucces.aspx");
}
Your TIME(7) needs to be HH:MM:SS at a minimum, and HH:MM:SS.NNNNNNN maximum. So, add :00 on your string for your TIME to make the conversion work. The DATE should be fine as long as you are using YYYY-MM-DD. You WILL get this error if you are using YYYY-DD-MM.

SQL Query inserting data into database

I am trying to insert date into database from Session DateValue by converting it into dateTime. The problem i am facing is its accepting the value of april month but when i am entering the value of March its giving error.
Please Help, The Query and the code i have used is as follow:
string a = Session["Date_Value"].ToString();
DateTime date= DateTime.Parse(a);
foreach (GridViewRow g1 in grdData.Rows)
{
//string Status = (g1.FindControl("TextBox1") as TextBox).Text;
//int Status = Convert.ToInt32(Sta);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Real_Attendance"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into Attendanc(Stu_id,Status,time,Date,Sub_id) values('" + g1.Cells[3].Text + "',#Status,'" + Session["Time_Value"].ToString() + "', #Date ,'" + Session["Sub_id"].ToString() + "')", con);
//SqlCommand cmd = new SqlCommand("Insert into Attendanc(Stu_id,Status,time,Date,Sub_id) values('" + g1.Cells[3].Text + "','"+ g1.Cells[1].Text +"','" + Session["Time_Value"].ToString() + "','" + Session["Date_Value"].ToString() + "','" + Session["Sub_id"].ToString() + "')", con);
//cmd.Parameters["#Status"].Value = ((Label)(g1.FindControl("Label1"))).Text;
cmd.Parameters.AddWithValue("#Status", ((Label)(g1.FindControl("Label1"))).Text);
cmd.Parameters.AddWithValue("#Date", date.ToShortDateString());
// cmd.Parameters.AddWithValue("#Date", date.ToShortDateString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
This is the code I am using to create session. I am creating session at webform3 And using its value at webform4
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Calendar1.Visible = false;
System.DateTime myDate = new System.DateTime();
myDate = Calendar1.SelectedDate;
txtDate.Text = myDate.ToString("dd/MM/yyyy");
Date = txtDate.Text;
day = Calendar1.SelectedDate.DayOfWeek.ToString();
Response.Write(day);
txtday.Text = day;
Session["Date_Value"] = Date;
//SelectTime();
}
I'm not sure this will solve your problem, but it will improve your code:
string a = Session["Date_Value"].ToString();
DateTime date= DateTime.Parse(a);
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Real_Attendance"].ConnectionString))
{
con.Open();
foreach (GridViewRow g1 in grdData.Rows)
{
using(SqlCommand cmd = new SqlCommand("Insert into Attendanc (Stu_id,Status,time,Date,Sub_id) values (#Stu_id, #Status, #Time, Convert(DateTime, #Date, 103), #Sub_id)", con))
{
cmd.Parameters.AddWithValue("#Stu_id", g1.Cells[3].Text);
cmd.Parameters.AddWithValue("#Status", ((Label)(g1.FindControl("Label1"))).Text);
cmd.Parameters.AddWithValue("#Time", Session["Time_Value"].ToString());
cmd.Parameters.AddWithValue("#Date", date.ToString("dd/MM/yyyy"));
cmd.Parameters.AddWithValue("#Sub_id", Session["Sub_id"].ToString());
cmd.ExecuteNonQuery();
}
}
con.Close();
}
First, I've changed sql statement to have only parameters. It's cleaner, safer, and easier to read and debug this way.
Second, I've changed the value that #Date parameter gets to a specific date format, and informed the database the expected format using the Convert function. this should fix your conversion problem.
Other improvements: I've moved the opening and closing of the connection outside of the foreach loop. there is no need to close and reopen the connection for each command execute. Also, I've moved the SqlConnection and the SqlCommand into using statements, as recommended by microsoft.

error Sql query with datetime

I got a error when I do the follow:
DateFrom has as datatype of datetime
My C# code:
string strQuery = "Select * FROM Agenda Where DateFrom='" + Calendar1.SelectedDate.Date.Date + "' ";
SqlCommand command = new SqlCommand(strQuery, Global.myConn);
da = new SqlDataAdapter(command);
da.Fill(Global.dsAgenda, "Tabel");
ddlActivity.DataSource = Global.dtAgenda;
ddlActivity.DataBind();
Calendar1 type:
Error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
You should prefer using parameters:
string strQuery = "SELECT * FROM Agenda WHERE DateFrom = #Date";
SqlCommand command = new SqlCommand(strQuery, Global.myConn);
command.Parameters.Add("#Date", SqlDbType.DateTime).Value = Calendar1.SelectedDate;
Use this
Convert(DateTime,Calendar1.SelectedDate.Date.Date,103)

Resources