0

所以我昨天写了这个问题。我仍在使用UPDATE下的解决方案,但由于某种原因,我现在收到FormatException was Unhandled错误消息。在错误下,编译器窗口显示Input string was not in a correct format. 为什么会发生这种情况?

当我查看错误时,我想也许我会更好地使用Int32.TryParse,就像在这个链接中一样。但这几乎是一样的交易。

这是我目前拥有的...

//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;
}

注意:我单击以显示此错误的节点中没有数字值。但是,他们的父母这样做(这是我不明白的,因为我将父母的传递header给了函数)。

谢谢你的帮助!

4

1 回答 1

0

那么Int32.TryParse不应该引发异常......

//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;
}

编辑

似乎你应该做这样的事情(当然,一些空检查会更好)

//Initializing a parent TreeView Item
var parentItem = (TreeViewItem)SelectedItem.Parent;
var header = (TextBlock)parentItem.Header;
int curNumber = getNumber(header.Text);
于 2013-08-22T14:49:44.167 回答