将字符串转换为Int32时,FormatException未处理

时间:2013-08-22 14:45:35

标签: c# wpf treeview formatexception

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

当我查看错误时,我认为使用Int32.TryParse可能会更好,就像在this link中一样。但这几乎是同样的交易。

这就是我现在所拥有的......

//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传递给了该函数。

感谢您的帮助!

1 个答案:

答案 0 :(得分: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;
}

编辑

似乎你应该做那样的事情(当然,somme null check会更好)

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