TreeView的问题!点一下节点马上报错
<div>这是前台代码
<asp:TreeView ID="Tree" runat="server" DataSourceID="XDS" ShowLines="True" OnSelectedNodeChanged="Tree_SelectedNodeChanged" OnTreeNodeCheckChanged="Tree_TreeNodeCheckChanged" OnTreeNodeDataBound="Tree_TreeNodeDataBound" Target="_self">
</asp:TreeView>
<asp:XmlDataSource ID="XDS" runat="server"></asp:XmlDataSource>
</div>
int zishu(string s1, string s2)
{
int i = -1, x = -1;
do
{
i = s1.IndexOf(s2, ++i);
x++;
} while (i != -1);
return x;
}
void run()
{
string path = Server.MapPath("/");
string[] s = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
for (int i = 0; i < s.Length; i++)
{
s[i] = s[i].Substring(path.Length);
s[i] = s[i].Replace("\", "/");
}
XmlDocument doc = new XmlDocument();
XmlElement xe = doc.CreateElement("根节点");
doc.AppendChild(xe);
int max = 0;
foreach (string str in s)
{
if (zishu(str, "/") > max)
{
max = zishu(str, "/");
}
}
foreach (string str in s)
{
for (int i = 0; i <= max; i++)
{
if (zishu(str, "/") == 0)
{
XmlElement xee = doc.CreateElement(str);
xee.SetAttribute("name", str);
xe.AppendChild(xee);
break;
}
else if (i != 0 && zishu(str, "/") == i)
{
string qian = str.Substring(0, str.LastIndexOf("/"));
string hou = str.Substring(str.LastIndexOf("/") + 1);
qian = "根节点/" + qian;
XmlElement xee = doc.CreateElement(hou);
xee.SetAttribute("name", hou);
XmlNode node = doc.SelectSingleNode(@qian);
node.AppendChild(xee);
break;
}
}
}
s = null;
s = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
for (int i = 0; i < s.Length; i++)
{
s[i] = s[i].Substring(path.Length);
s[i] = s[i].Replace("\", "/");
}
foreach (string str in s)
{
string ss = str.Replace(" ", "nul");
if (str.IndexOf("/") == -1)
{
XmlElement xee = doc.CreateElement(ss);
xee.SetAttribute("name", ss);
xe.AppendChild(xee);
}
else
{
string qian = ss.Substring(0, ss.LastIndexOf("/"));
string hou = ss.Substring(ss.LastIndexOf("/") + 1);
if (hou.Substring(0, 1) == ".")
{
hou = hou.Replace(".", "");
}
qian = "根节点/" + qian;
XmlElement xee = doc.CreateElement(hou);
xee.SetAttribute("name", hou);
XmlNode node = doc.SelectSingleNode(@qian);
node.AppendChild(xee);
}
}
doc.Save(Server.MapPath("/目录.xml"));
XDS.DataFile = Server.MapPath("/目录.xml");
}
求指点啊~~~~ treeview
[解决办法]
NullReferenceException说明有对象为null了,
另外,注意代码的执行顺序,
注意run()代码的运行与XmlDataSource加载数据源的执行顺序是谁先谁后