Mark
Mark

Reputation: 2760

Problem with condition statement in c#

if (txt_SendAt.Text != null)
{
    //string SendAt_date = txt_Respondby.Text;
    DateTime Send_date = Convert.ToDateTime(txt_SendAt.Text);

    param[15] = new MySqlParameter("@SendDate", MySqlDbType.DateTime);
    param[15].Value = Send_date;
    command.Parameters.AddWithValue("@SendDate", Send_date);     

}
else
{
    param[15] = new MySqlParameter("@SendDate", MySqlDbType.DateTime);
    param[15].Value = now;
    command.Parameters.AddWithValue("@SendDate", now);

}

I have a text box where i select date and time from a calender. When I leave the text box empty it should execute the statements in else condition but it executes the statement in if. Where am I going wrong

I am getting this error if i leave it blank String was not recognized as a valid DateTime.

Upvotes: 0

Views: 185

Answers (5)

stuartd
stuartd

Reputation: 73253

You're testing if the textbox itself is null, not it's text:

if (string.IsNullOrEmpty(txt_SendAt.Text) == false)

Upvotes: 5

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171411

Try:

if (!string.IsNullOrEmpty(txt_SendAt.Text))

Upvotes: 2

Stuart Thomson
Stuart Thomson

Reputation: 509

You should try change the if to

if ((txt_SendAt.Text != null)||(txt_SendAt.Text.Trim() != ""))

Upvotes: 0

Jodaka
Jodaka

Reputation: 1247

txt_SendAt refers to the textbox control. You want txt_SendAt.Text

Upvotes: 1

David Hoerster
David Hoerster

Reputation: 28701

Use String.IsNullOrWhitespace(txt_SendAt.Text) instead of checking for null.

You're checking if the control is null. It won't be null; you need to check if the Text property of the text box has a value. So if you use IsNullOrEmpty or IsNullOrWhitespace, you'll do a dual check -- if the control's property is null (unlikely) or if it's just blank space (or spaces).

Upvotes: 4

Related Questions