当我按下按钮时,如何使DataGridView不可见?

时间:2015-11-04 14:46:36

标签: vb.net

我有一个Button和一个DataGridView。当我按下按钮时,我希望DataGridview可见,当我再次按下它时,看不见

这是我到目前为止所尝试的:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim buttonId As New Button
    Dim dvg As New DataGridView
    Try
        dvg = DirectCast(sender, DataGridView)

        dvg.Visible = True
    Catch ex As Exception

    End Try
End Sub

我知道这个问题听起来很基本,但我很缺乏经验,所以非常感谢帮助

2 个答案:

答案 0 :(得分:1)

首先,我会将datagridview对象作为您的类的成员。 然后我会像这样打开和关闭它:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If dgv.Visible Then
        dgv.Hide()
    Else
        dgv.Show()
    End If
End Sub

希望这会有所帮助

答案 1 :(得分:0)

不确定动态添加控件是个好主意,但是......

Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
    Try
        Dim dgv As New DataGridView
        dgv.Name = "dgvN"
        dgv.Size = New Size(Me.ClientSize.Width - 20, 300)
        dgv.Top = Me.ClientSize.Height / 2 - dgv.Height / 2
        dgv.Left = Me.ClientSize.Width / 2 - dgv.Width / 2
        dgv1.BringToFront()
        Me.Controls.Add(dgv)  ' use Controls() of desired container

        Dim newButton As New Button
        newButton.Text = "DGV On/Off"
        newButton.Width = TextRenderer.MeasureText(newButton.Text, newButton.Font).Width + 20
        newButton.Tag = "dgvN"
        Me.Controls.Add(newButton)  ' use Controls() of desired container

        AddHandler newButton.Click, AddressOf DGVVisibleButtonClick

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub
Sub DGVVisibleButtonClick(sender As Object, e As EventArgs)
    Dim dgv As DataGridView = Me.Controls(sender.tag)
    dgv.Visible = Not dgv.Visible
End Sub