Search code examples
vb.netflowlayoutpanel

How to disable and get name for control in FlowLayoutPanel from ContextMenuStrip in VB.Net


My program contains buttons in a FlowLayoutPanel.
I want to disable any button when right click on it and click "Disable" in the ContextMenuStrip.

My code is:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For i As Integer = 0 To 30
            Dim btn As New Button
            btn.Name = i
            btn.Text = i
            btn.ContextMenuStrip = ContextMenuStrip1
            FlowLayoutPanel1.Controls.Add(btn)
        Next
    End Sub

End Class

enter image description here


Solution

  • declare a public varibale for keeping a control

        public ctrl as button = nothing
    

    you can create a right click by putting this code on mouse down...

    If e.Button <> Windows.Forms.MouseButtons.Right Then Return
            Dim cms = New ContextMenuStrip
    
            ctrl = sender
    
            Dim item1 = cms.Items.Add("Disable")
            item1.Tag = 1
            AddHandler item1.Click, AddressOf Disable
    end if 
    

    and in the diable sub you can code like this...

    Private Sub Disable()
        ctrl.enabled = false
    End Sub