【问题标题】:IndexOutOfRangeException on accessing attributes through String array?IndexOutOfRangeException 通过字符串数组访问属性?
【发布时间】:2009-06-25 02:03:21
【问题描述】:

我在 winform 上显示了一个 treeView。现在,当我单击 treeview 中的 xmlnode 时,它​​的属性会显示在列表框中。现在我已将整个逻辑划分为 UI 和后端部分。现在我想要我的后端类包含显示单击的 xml 节点的属性(名称和值)的方法,并将它们存储在一个数组中,并在 treev_AfterSelect 事件中作为字符串返回给我的前端类。我该怎么做?我需要将我单击 winform 的节点的属性存储在字符串数组中并显示在列表框中。这是我的 Backhand 类的代码 enter code here

public  string[] selectedNode(XmlNode eventNode)
    {
        XmlAttributeCollection attCol = eventNode.Attributes;
        string[] strArray = new string[attCol.Count];
         if (attCol != null)
            for( int i = 0; i <= attCol.Count;i++)
            {  strArray[i] = "Attribute name: " + attCol[i].Name+","+" Attribute value: " + attCol[i].Value;//IndexOutOfRange Exception
                    }
            return strArray;
    } 

这里我遇到了 IndexOutOfRangeException 异常:传入的索引超出范围。在这条线上

strArray[i] = "Attribute name: " + attCol[i].Name+","+" Attribute value: " + attCol[i].Value;

我的前端 ( UI ) 类包含此代码来检索属性和值,显示 它在列表框上。

private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
    {
        classObj = new MytreeNodeClass();
       listBox1.Items.Clear();
        XmlNode xNode = e.Node.Tag as XmlNode;
        string[] arrStr = classObj.selectedNode(xNode); 
        listBox1.Items.Add(arrStr); //Is this the correct syntax to retrieve the data in listbox??
     }

你能帮我解决我哪里出错了吗?准确地删除异常并成功运行代码的内容和位置?我不希望在反手中使用 Treenode。 谢谢....

【问题讨论】:

    标签: xml winforms exception events


    【解决方案1】:

    你在循环中走得太远了。

    for( int i = 0; i <= attCol.Count;i++)
    

    应该是

    for( int i = 0; i < attCol.Count;i++)
    

    【讨论】:

    • 嘿,谢谢你的回答,但在列表框中显示的是 String[] 数组你能告诉我在列表框中得到结果的正确代码是什么吗?谢谢...等待您的回复..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2013-06-06
    • 1970-01-01
    相关资源
    最近更新 更多