0

TreeViewコントロールに、選択したハード ディスク ドライブの構造が表示されています。私のaddToParentNodeでは、ツリー ビューが展開された後に呼び出しを行います。しかし、あるメソッドから別のメソッドにノードを渡すと、「オブジェクト参照がオブジェクトのインスタンスに設定されていません」という例外がスローされます。

void addToParentNode(TreeNode childNodes)
{
    DirectoryInfo getDir = new DirectoryInfo(childNodes.Tag.ToString());
    DirectoryInfo[] dirList = getDir.GetDirectories();
    foreach (DirectoryInfo dir in dirList)
    {
        TreeNode parentNode = new TreeNode();
        parentNode.Text = dir.Name;
        parentNode.Tag = dir.FullName;
        childNodes.Nodes.Add(parentNode);
    }
}

private void tv_fileExplore_AfterExpand(object sender, TreeViewEventArgs e)
{
    foreach (TreeNode item in e.Node.Nodes)
    {
        addToParentNode(item);
    }
}

誰かが私を正しい方向に向けることができますか?

4

2 に答える 2

2

あなたの質問へのコメントによるとTag、ツリーノードのプロパティはですnull

nullメソッド内のすべてのツリーノードに非値を割り当てていますaddToParentNodeが、どこかに開始があり、ルートノードを作成している必要があります。したがって、そのルートノードのTagプロパティはまだに設定されてnullいるようです。

于 2012-08-26T13:18:59.877 に答える
0

十分なコンテキストはありませんが、いくつかのセーフガードを追加し、例外を処理することができます (処理したい場合にのみ例外をキャッチします。たとえば、TreeNode にツールチップを追加して、このノードの何が問題なのかをユーザーに通知できます。

 void addToParentNode(TreeNode childNodes) 
    { 
        if ((childNodes != null) && (childNodes.Tag != null))
        {
            DirectoryInfo getDir = null;
            try {
               getDir = new DirectoryInfo(childNodes.Tag.ToString()); 
            }
            catch(SecurityException) {
                 childNodes.ToolTipText = "no access";
            }
            catch(PathTooLongException) {
                childNodes.ToolTipText = "path more then 254 chars";
            }
            catch(ArgumentException)
            {
               childNodes.ToolTipText = "huh?";
            }
            if (getDir!=null) && (!getDir.Exists) return;
            DirectoryInfo[] dirList = null;
            try {
               dirList = getDir.GetDirectories(); 
            }
            catch(UnauthorizedException) {
                childNodes.ToolTipText = "no access";
            }
            catch(SecurityException)
            {
                 childNodes.ToolTipText = "no access";
            } 
            if (dirList == null) return;
            foreach (DirectoryInfo dir in dirList) 
            { 
                TreeNode parentNode = new TreeNode(); 
                parentNode.Text = dir.Name; 
                parentNode.Tag = dir.FullName; 
                childNodes.Nodes.Add(parentNode); 
            } 
       }
    } 
于 2012-08-26T12:24:15.270 に答える