Reputation: 387
I am trying to compare a date I enter in a textbox in a DD.MM.YYYY
format and I get an error.
string txt = "select count(*) from cont where Data_deschiderii < " + Convert.ToDateTime(TextBox1.Text).ToString("DD.MM.YYYY");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(txt, conn);
int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
Response.Write(x);
How could I do it? I couldn't find ANYTHING on the internet
Upvotes: 0
Views: 2354
Reputation: 11
Try this.
try
{
DateTime Date1= Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
DateTime Date2 = Convert.ToDateTime(TextBox2.Text).ToString("yyyy-MM-dd HH:mm:ss");
if (Date1 > Date2)
{
Your Code...
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Upvotes: 0
Reputation: 6604
The best approach is to start using prepared, parameterized queries. They ensure that comparisons are done correctly, and they prevent the possibility of SQL injection attacks.
Your code would be rewritten like this:
string txt = "select count(*) from cont where Data_deschiderii < @compareDate;";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(txt, conn);
cmd.Parameters.Add("@compareDate", SqlDbType.Date);
cmd.Parameters["@compareDate"].Value = TextBox1.Text;
int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
Response.Write(x);
That is, I am assuming that your database field Data_deschiderii
is of a date
form of datatype.
Upvotes: 3
Reputation: 61
You should convert the datetime in timespan and then compare that timespan in seconds. In SQL you could convert the same using DateDiff function.
Upvotes: 0
Reputation: 2504
You need to convert the date time to something SQL understands.
var formattedDate = Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
And then use formattedDate
in your query
Upvotes: 0