2013-02-06 136 views
1

我正在VB.NET中创建文件资源管理器。除了一件事以外,一切都很顺利。当你点击动态创建的标签来“打开”一个文件夹时,我需要获取标签的值(所以我可以为它设置一个变量)。由于标签是动态创建的,我无法获取该值。因此该对象不存在。这里是我的代码:VB.NET文件资源管理器

Imports System.IO 
Public Class Form1 
    Dim Path As String 
    Dim FolderCount = 0 
    Dim FolderWidth = 128 
    Dim FolderHeight = 128 
    Dim WidthAndPadding = FolderWidth + 10 
    Dim HeightAndPadding = FolderHeight + 10 
    Dim FolderTitle As String 
    Dim CombinedWidth 
    Dim FolderRows = 0 
    Dim OnNewLine = False 
    Dim FolderTop = 0 
    Dim FolderLeft = 0 

Dim FullPath 
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    Me.AutoScroll = True 
    Path = "C:\Program Files\" 
    For Each Dir As String In Directory.GetDirectories(Path) 
     CreateFolders(Dir) 
    Next 
End Sub 
Public Sub CreateFolders(ByVal StrDirectory) 
    FolderTitle = StrDirectory.Substring(Path.Length) 
    Dim Folder As New Label 
    FolderLeft = WidthAndPadding * FolderCount 
    Folder.Left = FolderLeft 
    Folder.Top = FolderTop 
    Folder.Width = FolderWidth 
    Folder.Height = FolderHeight 
    Folder.Image = My.Resources.Folder 
    Folder.TextAlign = ContentAlignment.BottomCenter 
    If FolderTitle.Length > 15 Then 
     FolderTitle = FolderTitle.Substring(0, 15) + "..." 
    End If 
    Folder.Text = FolderTitle 
    Folder.Font = New Font("Arial", 9.5) 
    FolderCount += 1 
    CombinedWidth = FolderCount * WidthAndPadding 
    If CombinedWidth >= Me.Width Then 
     OnNewLine = False 
     If OnNewLine = False Then 
      FolderRows = FolderRows + 1 
      FolderCount = 0 
      CombinedWidth = 0 
      Folder.Left = FolderCount * FolderWidth 
      FolderTop = FolderRows * FolderHeight 
      Folder.Top = FolderTop 
      OnNewLine = True 
      'FolderCount += 1 
     End If 
    End If 
    Me.Controls.Add(Folder) 
    AddHandler Folder.DoubleClick, AddressOf Folder_DoubleClick 
    FullPath = Path + FolderTitle 
End Sub 

Private Sub Folder_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) 
    'MsgBox(Folder.Text) 
End Sub 

末级

+0

使用ListView。 – SLaks

+1

您应该启用'Option Strict'。 – SLaks

回答

3

事件处理程序的sender参数包含生成事件的标签。
您可以通过编写CType(sender, Label)将其重新投射到Label

+0

什么?我不知道我明白你的意思... –

+0

非常感谢。我所做的就是测试它:'MsgBox(sender.text)' –