Question Get a label inside the Panel sent via AddHandler

newnoodle

New member
Joined
Jan 2, 2016
Messages
1
Programming Experience
Beginner
Hello,
(I am using VS 2010 .NET 4.0)
I have a For loop that appears 20 Small Panels, and each panel has an inner label, and I want when I click the panel, a msgbox will show the conntent of the Label inside.
Like this:
i3QnWCf.png


I tried this:

VB.NET:
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            For i As Integer = 0 To 20
                       'Statements to add the Panels and the Labels here
                                   AddHandler panelA.MouseEnter, AddressOf PanelClick 'hover effect
                                   AddHandler panelA.MouseLeave, AddressOf PanelLeave  
            Next
End sub


And the PanelClick method:

VB.NET:
    Public Sub PanelClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim clickedpanel As Panel = DirectCast(sender, Panel)
        clickedpanel.BackColor = Color.Pink
        
        Dim lbl = clickedpanel.Controls.OfType(Of Label)().First


        MessageBox.Show(lbl.Text)
    End Sub

But the error:
VB.NET:
Error    1    'OfType' is not a member of 'System.Windows.Forms.Control.ControlCollection'.    E:\vb\RSchat\vb1\Form1.vb    70    19    vb1

I don't know what is going on with the code. Please help me to fix it.
 
The OfType(Of TResult) method can be called on any object that implements the IEnumerable interface, which Control.ControlCollection does. As such, that code is valid.

That said, in order to be able to call any extension method, you must have imported the namespace that it's type is a member of. OfType(Of TResult) is a member of the System.Linq.Enumerable class, declared in the System.Core.dll assembly. As such, your project must have referenced System.Core.dll and imported System.Linq. You can do both on the References page of the project properties.
 
Back
Top