Tuesday, March 1, 2011

C#: overwriting string value in if else statemnt?

I have a fairly simple if else statement in C# that looks something like this;

    string BodyContent = "";
    if (Request.Form["value1"] != "")
    {
        BodyContent = "bla bla 1";

    }

    else if (Request.Form["value2"] != "")
    {
        BodyContent = "bla bla 2";
    }
else if (Request.Form["value3"] != "")
{
    BodyContent = "bla bla 3";
}
else {
    BodyContent = "Error";
}

My problem is that even if Request.Form["value3"] does have a value it is the value from BodyContent in the value1 check that is visible. (It can only be one of the request form objects that has a value at any point in time, so it is not because both value1 and value3 has a request.form value)

What am i doing wrong?

From stackoverflow
  • Replace your Request.Form["valueX"] != "" with !string.IsNullOrEmpty(Request.Form["valueX"]) and see what that does for you.

    RickNZ : +1. If an entry in the Form array doesn't have a value, it will be null, not an empty string.
    cJockey : Spot on - it worked :-)
  • You're running a string of else-ifs, so the first condition that is true will set the variable, and no other condition will be checked. Are you certain the first two conditions are not true?

0 comments:

Post a Comment