ASP.NET使用TreeView显示文件的方法

时间:2021-12-01 12:23:23

本文实例讲述了ASP.NET使用TreeView显示文件的方法,是非常实用的技巧。分享给大家供大家参考。具体实现方法如下:

通常在ASP.NET中,TreeView的使用很普遍,这里详细讲述一下使用TreeView显示文件的方法。

1.首先加入TreeView控件:

?
1
2
3
<asp:TreeView ID="driverInfoView" runat="server" ImageSet="XPFileExplorer" OnTreeNodePopulate="driverInfoView_TreeNodePopulate">
     
</asp:TreeView>

2.当页面加载的时候,写下以下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
protected void Page_Load(object sender, EventArgs e)
{
    foreach (DriveInfo driverInfo in DriveInfo.GetDrives())
    {
      TreeNode newNode = new TreeNode();
      newNode.Expanded = false;
      newNode.PopulateOnDemand = true;
      newNode.Value = driverInfo.Name;
 
      if (driverInfo.IsReady)
      {
        newNode.Text = driverInfo.Name + "(" + driverInfo.VolumeLabel + ")";
      }
      else
      {
        newNode.Text = driverInfo.Name + "(还没准备好)";
      }
      this.driverInfoView.Nodes.Add(newNode);
    }
}

3.设置TreeView节点的事件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
protected void driverInfoView_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
    DirectoryInfo dictInfo = new DirectoryInfo(e.Node.Value);
 
    foreach (DirectoryInfo directory in dictInfo.GetDirectories())
    {
      TreeNode newNode = new TreeNode();
      newNode.Expanded = false;
      newNode.PopulateOnDemand = true;
      newNode.Text = directory.Name;
      newNode.Value = directory.FullName;
      e.Node.ChildNodes.Add(newNode);
    }
 
    foreach (FileInfo fileInfo in dictInfo.GetFiles())
    {
      TreeNode newNode = new TreeNode();
      newNode.Text = fileInfo.Name;
      newNode.Value = fileInfo.FullName;
      e.Node.ChildNodes.Add(newNode);
    }
}

相信本文所述实例对大家的asp.net程序设计有一定的借鉴价值。