Error while inserting date from textbox in asp.net - c#

I am new to C#, and learning. I have a SQL Server database where I have table record that has a column dob of data type date. I am trying to insert into dob from my textbox which has a value of 19-08-17 with the following code
datebox.Text = "19-08-17";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", datebox.Text);
com.ExecuteNonQuery();
But I get this error
Conversion failed when converting date and/or time from character string.
How can I solve this?

When you pass a variable to a DateTime column as a parameter, you need to convert the text to a DateTime variable before passing it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].Connect ionString);
// Convert the textbox text to a DateTime variable
DateTime myDate = DateTime.ParseExact(datebox.Text, "dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", myDate);
com.ExecuteNonQuery();

Related

How could I configure the MSSQLLocal default datetime format

I am writing a program to interact with MSSQLLocal DB using C# through winforms but I find a problem witht the default datetime, it is not the date time format we use in my countr, I wonder how could I through Sql client -sql default C# classes I could change the default date format for a database or All the existing databases?
this could let me to format the datetime https://learn.microsoft.com/en-us/sql/t-sql/statements/set-dateformat-transact-sql?view=sql-server-ver15
but this doesnt change the default dateformat, how can i change programatically the DB datetime default format?
some code example
var connectionstr = $#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DBname};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
var con = new SqlConnection(connectionstr);
con.Open();
string changeDate = $#"SET DATEFORMAT dmy;";
SqlCommand command = new SqlCommand(changeDate , con);
var res = command.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand(InsertCmd, con);
SqlDataAdapter adapter = new SqlDataAdapter() { InsertCommand = cmd };
adapter.InsertCommand.ExecuteNonQuery();
adapter.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
command.Dispose();
The datetime object in the database is just a datetime, the data can be set to a certain format when displaying in WinForm if you require it. For example, if i wanted the datetime to be display in the UK format:
DateTime.Now.ToString("dd/MM/yyyy")
Datetime Format
Turns out before adding a new value to the row you would need to include in the string CAST(01/01/2020) as dateformat

Insert date in to database from dd/MM/yyyy formatted string

In windows form I have DateTimePicker with custom format dd/MM/yyyy.
I want to insert the selected date to SQL Local DB but it throwing an exception.
Conversion failed when converting date and/or time from character string
my question is:
How to insert this date into a database in any format.
Here is my code
string query = "Insert into myTable Values('" + dateTimePicker1.Text + "');";
Use DateTimePicker.Value instead of DateTimePicker.Text. If you only want the date part, you could use DateTimePicker.Value.Date.
DateTimePicker.Value is the actual DateTime object assigned to the control, whereas DateTimePicker.Text is the Value property with formatting applied. Using Value directly saves you from having to convert the Text to a DateTime first.
You should also use a parameterized query, as others have noted.
string query = "Insert into myTable Values (#myDate)";
using(SqlConnection connection = new SqlConnection(connectionString))
{
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("myDate", dateTimePicker1.Value);
}
}

Conversion date when storing in a table

I have a field date in DataTable
jeudi 12 mars 2015
vendredi 13 mars 2015
samedi 14 mars 2015
I need to store it in a table in sql server test which have a column datedes type date
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES('" + dt.Rows[i][j] + "')", con);
command.ExecuteNonQuery();
The code above always return error in conversion date.
how to resolve it ?
You need something like this:
Convert your rows[i][j] to a DateTime
use properly parametrized query in ADO.NET to insert your date
Code something like this:
// this might not work right now - you need to adapt this to that
// you can convert your strings like 'vendredi 13 mars 2015' to a
// valid "DateTime" object
DateTime dateTimeFromRow = Convert.ToDateTime(dt.Rows[i][j]);
// set up your DB connection string
string connectionString = "....";
// define your insert query with PARAMETERS
string insertQuery = "INSERT INTO [test]([Datedes]) VALUES(#DateDes);";
// use "using" blocks to properly dispose of connection and command
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(insertQuery, conn)
{
// define and set value for parameter
command.Parameters.Add("#DateDes", SqlDbType.Date);
command.Parameters["#DateDes"].Value = dateTimeFromRow;
// open connection, execute INSERT, close connection
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
In your example, you try to insert a string to your date type table column which is wrong obviously.
Depending on what you are doing;
Change your date typed column to nvarchar and insert that string
Parse your string to DateTime and insert that value with parameterized query.
For first option, just change your column type to nvarchar.
For second option, you need parse your string with fr-FR culture (if it is not your CurrentCulture) and pass this value directly.
var s = "samedi 14 mars 2015";
var dt = DateTime.Parse(s, CultureInfo.GetCultureInfo("fr-FR"));
using (var con = new SqlConnection(conString))
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO [test] ([Datedes]) VALUES(#date)";
cmd.Parameters.Add("#date", SqlDbType.Date).Value = dt;
con.Open();
cmd.ExecuteNonQuery();
}
What you are doing wrong is you try to parse data type string to datetime. And from your information the datetime format is not legal to parse. I suggest you to create another string type's field to store 'jeudi' 'vendredi' or 'samedi'.
Use to cut string :
var targetString = "jeudi 12 mars 2015";
var resultString = "";
int index;
foreach (var item in targetString)
{
if (int.TryParse(item.ToString(), out index) && !string.IsNullOrWhiteSpace(item.ToString()))
{
resultString = targetString.Substring(index);
}
}
//resultString == "12 mars 2015"
Afterthat use :
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES("#date")", con);
command.Parameters.AddWithValue(#date, resultString);
command.ExecuteNonQuery();
Do not append string like you do because it's not secure.

Converting data entered by user to date

I'm trying to insert data of type 'date' from a textbox on my form to the database.
I want to ensure data entered by the user is stored in the format'dd/mm/yyyy' in the database. I have a column in the database of type 'date' but when i enter values of the format above, i get an exception (something like: cannot implicitly convert varchar to type date).
Please how do I convert date entered to the format 'dd/mm/yyyy'. I tried using CONVERT((varchar,getdate(),103) AS [DD/MM/YYYY]) but i cant figure out where to place it in my code. I'm new to c# and sql server, help please!!
It's better to not convert the date in SQL, and just pass it back as a date, and then within C# you can structure it however you want
myDate.ToString("dd/mm/yyyy")
use parameterised queries:
DateTime dt;
dt = DateTime.ParseExact(TextBox1.Text,
"dd/MM/yyyy",CultureInfo.InvariantCulture);
SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "INSERT INTO [TABLENAME](DateCol) VALUES(#DateValue)";
SqlCommand cmd=new SqlCommand(query,con);
cmd.Parameters.AddWithValue("#DateValue",dt);
con.Open();
cmd.ExecuteNonQuery();
EDIT: from your comments :
i want the date to also be displayed in the same 'dd/MM/yyyy' format
in the database
You can can not control underlying Database how it displays or manages your Date in Database but if you want to get the date in format of dd/MM/yyyy while reading from database you can try the below:
SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "SELECT [DateCol] FROM TABLENAME]";
SqlCommand cmd=new SqlCommand(query,con);
con.Open();
SqlReader reader = cmd.ExecuteReader();
while(reader.Read())
{
DateTime dt= Convert.ToDateTime(reader["DateCol"].ToString());
string mydateString = dt.ToString("dd/MM/yyyy");
}
con.Close();

How to compare 2 dates taken from datetimepicker in select query?

I have 2 datetimepickers. In my select query i want to fetch records between these dates. datatype for date in database in varchar(MAX). For datetimepicker i have set custom format as dd-MM-yyyy. Here is my sql query
SqlDataAdapter da = new SqlDataAdapter("Select custname From tb_customer WHERE date >= '"+dtp_fromdate.Text+"' AND date <= '"+dtp_todate.Text+"'", con);
For eg: if my start date is 9-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and 11-06-2012
Incase if my start date is 10-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and not 11-06-2012
Please help
Use Convert or Cast T-SQL to convert VARCHAR value to Date or DateTime and also learn/use parameters instead of hard-coded SQL string.
The problem lies in lack of use of parameters. Using parameters will avoid any minsunderstanding between you and yuor database backend
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter da = new SqlDataAdapter();
string query = "Select custname From tb_customer WHERE date >= #from AND date <= #to"
da.SelectCommand = new SqlCommand(queryString, con);
da.SelectCommand.AddWithValue("#from" , dtp_fromdate.Value);
da.SelectCommand.AddWithValue("#to" , dtp_to.Value);
da.Fill(ds);
return ds;
}

Categories

Resources