如何在VB.NET表单中放置用户控件表单?

时间:2014-03-21 16:20:20

标签: vb.net

我希望能够通过单击按钮显示用户控件表单。我无法使用.show()显示表单,因为我可以使用常规表单。

问题:如何在VB.net表单中放置用户控件表单?

我应该重新解释这个问题。如何在表单中显示用户控件表单。当我构建表单时,我并不完全确定这是否有效。

代码:

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim MyDialog As New ColorDialog()
        ' Keeps the user from selecting a custom color.
        MyDialog.AllowFullOpen = True
        ' Allows the user to get help. (The default is false.)
        MyDialog.ShowHelp = True
        ' Sets the initial color select to the current text color,
        MyDialog.Color = TextBox1.ForeColor

        ' Update the text box color if the user clicks OK  
        If (MyDialog.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            TextBox1.ForeColor = MyDialog.Color
        End If
    End Sub

    Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
        Dim myCoolFile As String = "C:\Users\itpr13266\Desktop\test.txt" '// your file location.
        Dim tempStr As String = IO.File.ReadAllText(myCoolFile) '// read file into a String.
        Dim x As Integer = tempStr.Length - 1 '// get String length, Index based, starting at 0 not 1.
        Dim myArray(x) As String '// create your String Arrays.
        Dim i As Integer = 0 '// Integer used to increase Array #'s.

        For Each myChr As Char In tempStr '// loop thru each each character in the String.
            myArray(i) = myChr '// add values to each String Array.
            i += 1 '// increase count for next Array.
        Next

        For number As Integer = 1 To myArray.Length - 1 Step 1 'loops through the array by 1 and to 1 less the length
            Debug.Write(myArray(number)) 'write the value in the array to the debug window
        Next
    End Sub

    Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
        UserControl1.Show()
    End Sub
End Class

2 个答案:

答案 0 :(得分:2)

这里有两个解决方案。一种是在项目中创建一个新的Form并让它托管UserControl。然后,在Form方法中实例化Button6_Click(代码类似于ColorDialog方法中的Button1_Click代码)。另一种解决方案是直接在Button6_Click处理程序中实例化占位符表单,如下所示:

Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
    Using UserControl1 As FooUserControl = New FooUserControl()
        Using tmpForm As Form = New Form()
            tmpForm.Width = UserControl1.Width
            tmpForm.Height = UserControl1.Height
            tmpForm.Controls.Add(UserControl1)
            tmpForm.ShowDialog()
        End Using
    End Using
End Sub

老实说,第一种方法更简洁,通过利用WinForms Designer作为主机表单,您可以更好地控制UserControl的呈现方式。

答案 1 :(得分:1)

在调用

之前尝试将可见性设置为True
UserControl1.Visible = True