vb.net可以在Usercontrol中显示Harddrive的VolumeLabel吗?

时间:2017-04-04 05:29:09

标签: vb.net

我尝试从计算机系统中显示硬盘列表 但我发现我无法在“标签”用户控件中显示它

我在messagebox.show()上试试,这项工作正常 任何人都可以指出我的代码有什么问题? 或者只是vb.net中的某个对象可以显示volumelabel的字符串? 谢谢

这是我的代码:

private sub getDriveInfo

    for each driveList as DriveInfo in DriveInfo.GetDrives()

        dim _label as label = new label
        dim localStorage as new list(of string)

        'localStorage.Add(driveList.VolumeLabel) this doesn't works
        '_label.Text = driveList.VolumeLabel) this doesn't work as well
        'label.Location = new point(10,10)
        'Messagebox.Show(driveList.VolumeLabel) this works properly
    Next

end sub

还有一个我发现的bug,如果我调用这个方法,我的用户控件就会消失,

示例

private sub new()

getDriveInfo() 'if i don't call this method, my user control at below is visible

Dim _textbox as textbox = new textbox

with _textbox

    .location = new point(50,50)
    .font = new font("arial", 10, regular) 'after the method is called, this disappear

end with

controls.add(_textbox)
end sub

1 个答案:

答案 0 :(得分:0)

在这两个示例中,您必须设置控件的Parent:

_label.Location = New Point(10, 10)
_label.Parent = Me

...或者将其添加到表单/控件的控件集合中(例如,您的UserControl.Controls()集合):

_label.Location = New Point(10, 10)
Me.Controls.Add(_label)

另请注意,默认Label控件启用了AutoSize属性,这意味着它将不会显示为多行/所有驱动器标签,直到您禁用自动调整大小并调整标签大小以适应文本。对于TextBox,您需要启用TextBox.MultiLine属性并调整控件的大小

一个例子:

Friend LabelDrives As New Label()

Private Sub BuildAndShowDriveLabel()

    Dim sb As New StringBuilder()
    For Each drive As DriveInfo In DriveInfo.GetDrives()
        ' Not ready drives will throw an exception so we do a sanity check.  
        ' (eg. DVD-ROM drives that are loading a disc)
        If (drive.IsReady) Then 
            sb.AppendLine(drive.VolumeLabel)
        End If
    Next drive

    With Me.LabelDrives
        .SuspendLayout()
        .Parent = Me
        .Text = sb.ToString()
        .AutoSize = False
        .Size = New Size(TextRenderer.MeasureText(.Text, .Font))
        .Location = New Point(10, 10)
        .ResumeLayout(False)
    End With

End Sub