2013-08-22 34 views
0

所以我昨天写了this question。我仍在使用更新下的解决方案,但由于某些原因,我现在收到FormatException was Unhandled错误。在该错误下,编译器窗口显示Input string was not in a correct format。为什么会发生这种情况?FormatException将字符串转换为Int32时未处理

当我看到这个错误时,我想我可能会用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传递给函数)。

感谢您的帮助!

回答

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); 
+0

好吧,照顾了例外。但'Int32.TryParse'失败,因为'curNumber'返回0.有什么我可以告诉你,这将有助于你解释为什么? –

+0

@Ericafterdark好吧,你应该尝试缓慢的调试,看看有什么在parentItem,然后在parentItem.Header ... –

+0

那么我的父节点的头设置为'TextBlock',这是一个问题吗?在if语句中,我得到了'parentItem'的正确值,但是当它传递给'getNumber'时,'parentNodeHeader'显示''System.Windows.Controls.TextBlock'',因为它是Value。 –

相关问题