Conversion failed - asp.net

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.

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();
}

Need algorithm For room reservation

I need a room reservation algorithm that room should not be book before its date once a room is booked should not be book on that similar date. I am using sql server and was using status active or booked but its not working.
public void res(DateTime? arrivalDate,DateTime? departureDate)
{
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = (#"Server=DESKTOP-8JJO9NL\SQLEXPRESS;Database=HMS;Trusted_Connection=True");
myConn.Open();
SqlCommand com = new SqlCommand();
com.Connection = myConn;
string sql = "";
sql = "select count(*) from Roomsdata where Room#=#roomnum and Status='Active and arrivaldate >= #arrivalDate and departure <= #departureDate'";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#roomnum", Roomnum);
com.Parameters.AddWithValue("#arrivalDate", arrivalDate);
com.Parameters.AddWithValue("#departureDate", departureDate);
int numRecords = (int)com.ExecuteScalar();
if (numRecords == 1)
{
SqlConnection myConn2 = new SqlConnection();
myConn2.ConnectionString = (#"Server=DESKTOP-8JJO9NL\SQLEXPRESS;Database=HMS;Trusted_Connection=True");
myConn2.Open();
SqlCommand myCmd = new SqlCommand("update Roomsdata set [customername]=#customername ,[contact] =#contact ,[arrivaldate]=#arrivaldate,[departure]=#departure ,[Status]='Booked' ,[stayingdays]=DATEDIFF(day,arrivaldate,departure) ,[Total amount]=DATEDIFF(day,arrivaldate,departure)*1278 FROM [HMS].[dbo].[Roomsdata] where Room#=#roomnum1", myConn2);
myCmd.Parameters.AddWithValue("roomnum1", Roomnum);
myCmd.Parameters.AddWithValue("#customername", Costumername);
myCmd.Parameters.AddWithValue("#contact", Contact);
myCmd.Parameters.AddWithValue("#arrivaldate", Arrivaldate);
myCmd.Parameters.AddWithValue("#departure", Departuredate);
myCmd.ExecuteNonQuery();
myConn2.Close();
}
else
{
throw new Exception("Room is Already Booked");
}

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.

Fetching Data from database as per details

string date = ddlShowDates.SelectedValue.ToString();
cmd = new SqlCommand("SELECT tbl_Shows.ShowTime FROM tbl_Shows INNER JOIN tbl_MovieTimings ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId WHERE tbl_MovieTimings.Date='" + date + "'", con);
I want to display show time in dropdownlist as per date is selected.
Always use sql-parameters instead of string concatenation to prevent sql-injection.
I guess you have a second DropDownList which should be filled from the first:
DateTime date = DateTime.Parse(ddlShowDates.SelectedValue);
string sql = #"SELECT tbl_Shows.ShowTime
FROM tbl_Shows
INNER JOIN tbl_MovieTimings
ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId
WHERE tbl_MovieTimings.Date=#Date";
using(var con = new SqlConnection("ConnectionString"))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#Date", SqlDbType.Date).Value = date;
con.Open();
using(var rd = cmd.ExecuteReader())
{
while(rd.Read())
{
TimeSpan time = rd.GetTimeSpan(0);
timeDropDownList.Items.Add(time.ToString());// change format as desired in TimeSpan.ToString
}
}
}

Conversion failed when converting datetime from character string 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.

Resources