0

I have a class that I am passing a value too from my textbox. I use int? in the class I am passing too, to allow null values. Every-time I execute it gives the input string is not in correct format error. How can I get it to allow the null value? I thought about creating an if statement that just passes string = "null". I put my code below thank you in advance.

This is what I use to pass the values to my class that gives the error when I leave it blank.

newGrid.EmployeeID = Convert.ToInt32(employeeIDTextBox.Text);
newGrid.JobID = Convert.ToInt32(JobIDTextBox.Text);

Variable declaration in my class that the info is passing to.

public int? JobID { get; set; }

3 Answers 3

6

Use TryParse instead:

Int32 employeeId;
newGrid.EmployeeID = Int32.TryParse( employeeIDTextBox.Text, out employeeId ) ? employeeId : null;

This does require multiple lines of statements. You could wrap TryParse to simplfy this, like so:

public static Int32? Int32TryParseSafe(String text) {
    Int32 value;
    return Int32.TryParse( text, out value ) ? value : null;
}

// Usage:
newGrid.EmployeeID = Int32TryParseSafe( employeeIDTextBox.Text );
Sign up to request clarification or add additional context in comments.

3 Comments

Ok so use the second method or both?
Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'
I got it needed (int?) ex: ? (int?)value
1
      int number;
      bool result = Int32.TryParse(employeeIDTextBox.Text, out number);
      if (result)
      {
         newGrid.EmployeeID=number;       
      }
      else
      {
      //whatever you want to do for bad values
      newGrid.EmployeeID=0;
      }

Comments

1

You won't be able to convince Convert.ToInt32 to change its behavior, but you can easily get the effect you want yourself:

string employeeID = employeeIDTextBox.Text;
newGrid.EmployeeID = string.IsNullOrEmpty(employeeID) ? null : Convert.ToInt32(employeeID);

Note that while this is less verbose than some other options, you aren't as safe as you are with TryParse. If the user enters non-numeric characters this will fail.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.