2010-09-01 29 views
0

我有一個樹狀視圖和一個根節點。我已經寫MouseHoverEvent如下MouseHover在樹狀視圖的根節點上

private void tvwACH_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e) 
    { 

     string strFile = string.Empty; 
     if (e.Node.Parent.Text == "FileHeader") 
     { 
      strFile = e.Node.ToString(); 

      string str = strFile.Substring(10); 
      StringComparison compareType = StringComparison.InvariantCultureIgnoreCase; 
      string fileName = Path.GetFileNameWithoutExtension(str); 
      string extension = Path.GetExtension(str); 
      if (extension.Equals(".txt", compareType)) 
      { 

       StringBuilder osb = new StringBuilder(); 
       objFileHeader.getFileHeader(str, out osb); 
       e.Node.ToolTipText = Convert.ToString(osb); 
      } 
     } 

    } 

但是,如果我有我的鼠標根節點爲空抗辯處理我收到一個錯誤。如果我把鼠標懸停在根節點上,什麼都不應該發生。請任何人幫助我。

回答

1
private void tvwACH_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e) 
{ 
    string strFile = string.Empty; 

    // the problem is here, root node does not have a parent 
    // also added a fix 
    if (e.Node.Parent != null && e.Node.Parent.Text == "FileHeader") 
    { 
      strFile = e.Node.ToString(); 

      string str = strFile.Substring(10); 
      StringComparison compareType = StringComparison.InvariantCultureIgnoreCase; 
      string fileName = Path.GetFileNameWithoutExtension(str); 
      string extension = Path.GetExtension(str); 
      if (extension.Equals(".txt", compareType)) 
      { 
       StringBuilder osb = new StringBuilder(); 
       objFileHeader.getFileHeader(str, out osb); 
       e.Node.ToolTipText = Convert.ToString(osb); 
      } 
    } 
} 
0

根節點沒有父節點集。所以你不應該引用e.Node.Parent.Text作爲根節點。 您需要使用條件語句來檢查此節點是否爲根節點。如果當前節點 是root,則應正確處理它。您也可以處理異常以解決此問題。