Click here to Skip to main content
15,894,539 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
How can I add my object (for example button1) to UserControl1?

I used below code but doesn't work:

VB
Dim btn as Button
btn = new Button
UserControl1.Controls.Add (btn)
Posted
Updated 9-Dec-13 4:25am
v2
Comments
Sh.H. 9-Dec-13 10:30am    
Any answer please????? :(
Sergey Alexandrovich Kryukov 9-Dec-13 10:54am    
Answer to what? What "does not work", exactly?
—SA
Sh.H. 9-Dec-13 11:26am    
I mean if you copy/paste this code to project, it gives me error.
phil.o 9-Dec-13 10:34am    
Maybe try to give your button at least a minimum size and a discrimining text?
Sh.H. 9-Dec-13 10:41am    
What do you mean Phil.o ?

1 solution

The recommended way in not to do it from outside the UserControl, but to do it from inside the control instead.
So create a method which adds it:
VB
Public Sub New(text As String)
    Dim but As New Button()
    but.Text = text
    but.Location = New Point(10, 10)
    but.Click += New EventHandler(AddressOf button_Click)
    Controls.Add(but)
End Sub
Then just add the handler method itself:
VB
Protected Sub button_Click(sender As Object, e As EventArgs)
' Handler code here
End Sub
 
Share this answer
 
Comments
Sh.H. 9-Dec-13 15:58pm    
Thanks..... But it is not what I want.
Follow your code, the button adds on Form1, not on UserControl1

I added a UserControl from solution , right click on project name, add>User Control

I hope I explained clear ....
OriginalGriff 9-Dec-13 16:31pm    
No, the method goes inside the UserControl, so the button is added to the control controls collection, not the form. The user control can't affect the form since it had no access to it (or even knows it is contained within a form, not another control)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900