且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在winfoms中将动态用户控件添加到面板思想名称?

更新时间:2023-12-02 23:23:28

不确定是否这是问题所在,假设您正在使用VB.Net(而不是标签所说的C#)。



 pnHolder.control。 add(ctl)





它应该是:



pnHolder。控件 .add(ctl)



您还应该声明用户控件,然后才能在代码中使用它。例如,我有一个名为_clUserControl的UserControl类。在您希望将UserControl添加到Panel控件的表单中,您必须首先声明UserControl,例如:



 私有 clUserControl 作为  _clUserCOntrol  声明用户控件 





在您希望将控件添加到Panel Control的代码中,只需添加控件:



 myPanel.Controls 。新增(clUserControl)


i am made a project (windows form, vb.net)
My mean is how to add dynamic a user control to panel by name of user control.
I had made with form by below:

Dim a As Assembly = Assembly.GetEntryAssembly()
           Dim t As System.Type = a.[GetType](formName)
           Dim o As Object = System.Activator.CreateInstance(t, True)
           Dim frm As Form = DirectCast(o, Form)


frm.show()

but I can't with user control

Dim a As Assembly = Assembly.GetEntryAssembly()
Dim t As System.Type = a.[GetType](controlName)                        ' -->nothing
          Dim o As Object = System.Activator.CreateInstance(t, True)
          Dim ctlAs System.Windows.Forms.UserControl= DirectCast(o, System.Windows.Forms.UserControl)</pre>
pnHolder.control.add(ctl)          


Can You help me, Plz?

Not sure if this is the problem, assuming you are using VB.Net (and not C# as the Tag says).

pnHolder.control.add(ctl)



It should read:

pnHolder.controls.add(ctl)

You should also declare your user control before you can use it in your code. For example, I have a UserControl Class called _clUserControl. In the form where you wish to add the UserControl to the Panel control, you have to declare the UserControl first, e.g.:

Private clUserControl As New _clUserCOntrol 'Declare the User Control



In your code where you wish to add the control to the Panel Control, simply add the the control:

myPanel.Controls.Add(clUserControl)