运行时设计

时间:2011-12-06 07:41:26

标签: vb.net runtime

我是vb.net的新手,我只想问你一些问题。 我想创建一个简单的程序,我正在尝试使用运行时设计。

enter image description here

使用此表单,当您单击带有标题(文本)“显示另一个表单”的button1时,将使用以下代码创建另一个表单:

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim NewForm As New Form
        Dim btnCancel As New Button

        NewForm.StartPosition = FormStartPosition.CenterScreen
        NewForm.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        NewForm.BackColor = Color.WhiteSmoke
        NewForm.Size = New Size(400, 200)
        NewForm.FormBorderStyle = Windows.Forms.FormBorderStyle.Sizable


        btnCancel.Text = "Cancel"
        btnCancel.Size = New Size(150, 50)
        btnCancel.Location = New Point(50, 50)

        NewForm.Controls.Add(btnCancel)
        NewForm.ShowDialog()

        AddHandler btnCancel.Click, AddressOf CancelClick
    End Sub

    Public Sub cancelclick(ByVal sender As Object, ByVal e As EventArgs)
        Dim x As String = MessageBox.Show("Exit", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
        If x = vbYes Then End
    End Sub
End Class

enter image description here

如何在单击“取消”按钮时退出我创建的表单。我提供的代码不起作用。请帮助我。感谢

2 个答案:

答案 0 :(得分:4)

在显示对话框之前尝试附加处理程序代码

  

NewForm.Controls.Add(btnCancel)
  AddHandler btnCancel.Click,AddressOf CancelClick
  NewForm.ShowDialog()

答案 1 :(得分:0)

在您的代码中,将AddressOf CancelClick更改为AddressOf cancelclick

编辑:

将NewForm.ShowDialog()更改为NewForm.Show(),并将代码更改为以下代码,然后肯定会有效。

    Public NewForm As Form
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        NewForm = New Form
        Dim btnCancel As New Button

        NewForm.StartPosition = FormStartPosition.CenterScreen
        NewForm.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        NewForm.BackColor = Color.WhiteSmoke
        NewForm.Size = New Size(400, 200)
        NewForm.FormBorderStyle = Windows.Forms.FormBorderStyle.Sizable


        btnCancel.Text = "Cancel"
        btnCancel.Size = New Size(150, 50)
        btnCancel.Location = New Point(50, 50)

        NewForm.Controls.Add(btnCancel)
       AddHandler btnCancel.Click, AddressOf cancelclick

        NewForm.Show()

     End Sub

    Public Sub cancelclick(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim x As String = MessageBox.Show("Exit", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
        If x = vbYes Then End 
    End Sub