Evren Ozturk
Evren Ozturk

Reputation: 928

How to access form controls from within custom control

OK it's little strange for me. I never used something like this. I have a form named VBProject It has two TextBoxes and one custom control named MyControl which is created in another project. MyControl's project has a form inside, named Form3. When My control is loaded it needs to find all controls in my VBProject and add them into a listbox which is in Form3. Then Show the Form3. In the end ListView need to shows name and text of textboxes but it shows nothing. Here are my codes:

MyControl's Load_Event:

Dim i As Integer = 0
MessageBox.Show("Control Count:" + Me.Controls.Count.ToString)
For Each MyObject In Me.Controls
    If TypeOf MyObject Is TextBox Then
        MessageBox.Show("Found a textbox")
        Dim lviNew As New ListViewItem
        lviNew.Text = i.ToString()
        lviNew.SubItems.Add(MyObject.Name)
        lviNew.SubItems.Add(MyObject.Text)
        Form3.SetVal(lviNew)
        i += 1
    End If
Next
Form3.Show()

SetVal Function in Form3

Public Sub SetVal(ByVal lviNew As ListViewItem)
    lstName.Items.Add(lviNew)
End Sub

Picture of project

enter image description here

A:VBProject-B:MYControl Execute-C:MyControl's Project's Form3

I hope explained it well. Thank you for your time.

Upvotes: 1

Views: 2234

Answers (1)

H-Man2
H-Man2

Reputation: 3189

You can access the controls of the form a custom control is located on by using

Me.ParentForm.Controls

The controls of the parent which could for example be a panel can be accessed by

Me.Parent.Controls

You used Me.Controls which refers to the controls owned by the custom control itself.

I don't know exactly, but you might get problems when using this in the load event of the control, because other controls of the parent form might be loaded after the custom control.

Upvotes: 2

Related Questions