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
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.
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
You should convert the datetime in timespan and then compare that timespan in seconds. In SQL you could convert the same using DateDiff function.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.