Search code examples
c#wpftreeviewformatexception

FormatException was Unhandled while converting string to Int32


So I wrote this question yesterday. I am still using the solution under UPDATE, but for some reason I am now receiving a FormatException was Unhandled error. Under the error, the compiler window says that the Input string was not in a correct format. Why would this be happening?

When I was looking into the error I thought that maybe I'd have better luck using Int32.TryParse, like in this link. But it was pretty much the same deal.

This is what I currently have...

//Initializing a parent TreeView Item
TreeViewItem parentItem = (TreeViewItem)SelectedItem.Parent;

//This is the call to getNumber that I am having trouble with.
//It is located in an if statement, but I didn't bother to write out the
//whole statement because I didn't want to add surplus code
int curNumber = getNumber(parentItem.Header.ToString());

//Gets the number contained in a Node's header
public static int getNumber(string parentNodeHeader)
{
      int curNumber = 0;
      curNumber = Convert.ToInt32(parentNodeHeader); //**FormatException!!
      return curNumber;
}

Note: The nodes that I click on to make this error appear do not have number values in them. However, their parents do (Which is what I don't understand because I am passing the parent's header to the function).

Thanks for your help!


Solution

  • Well Int32.TryParse should not raise an exception...

    //Gets the number contained in a Node's header
    public static int getNumber(string parentNodeHeader)
    {
          int curNumber;
          //if parse to Int32 fails, curNumber will still be 0
          Int32.TryParse(parentNodeHeader, out curNumber);
          return curNumber;
    }
    

    EDIT :

    Seems that you should do something like that (somme null check would be better, of course)

    //Initializing a parent TreeView Item
    var parentItem = (TreeViewItem)SelectedItem.Parent;
    var header = (TextBlock)parentItem.Header;
    int curNumber = getNumber(header.Text);