TextBox字符串未被识别为有效的DateTime

时间:2016-01-27 00:04:53

标签: c# datetime

我只需要对下面的代码有所帮助。我得到的字符串没有从这一行被复制为有效的DateTime。我尝试使用DateTime.TryParse,但它只是给了我错误,Convert.ToDateTime给了我同样的错误。

   if(DateTime.Parse(TextBox3.Text)>=d1 && DateTime.Parse( TextBox4.Text)<=d2)
    {
protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source = KEVS; Initial Catalog = booking; Integrated Security = True; ");
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    SqlDataReader dr;
    con.Open();
    cmd = new SqlCommand("select * from booking1 where busno='" + DropDownList1.SelectedItem.Text + "'", con);

   // cmd.CommandText = "Select * from booking1 where date='" + TextBox3.Text + "' and busno='" + DropDownList1.Text + "'";
    dr = cmd.ExecuteReader();
    if (dr.Read())
    {
         d1 = dr.GetDateTime(2);
         d2 = dr.GetDateTime(3);
    }

   if(DateTime.Parse(TextBox3.Text)>=d1 && DateTime.Parse( TextBox4.Text)<=d2)
    {
         Label14.Text = "bus is already booked by someone";
    }

1 个答案:

答案 0 :(得分:0)

要解决这个直接问题,请使用DateTime.TryParse代替DateTime.Parse,因为您正在处理用户输入。如果您知道该值是实际的DateTime表示,则仅使用Parse。

DateTime dt3;
DateTime dt4;

if(DateTime.TryParse(TextBox3.Text, out dt3) && dt3 >=d1 && DateTime.TryParse(TextBox4.Text, out dt4) && dt4 <=d2)

然后根据需要使用dt3dt4的值。