怎样在vb中,动态添加一个控件?如:textbox 原来窗体上没有的,现在想用代码实现添加,怎么实现?
顶的有分!

解决方案 »

  1.   

    Set cmdObject = Form1.Controls.Add("VB.CommandButton", "cmdOne")
       cmdObject.Visible = True
       cmdObject.Caption = "Dynamic CommandButton"
      

  2.   

    '先声明对象变量为 CommandButton 。
    Private WithEvents cmdObject As CommandButton
      

  3.   

    通过Add方法实现
    Add方法在Controls集合中添加一个控件并返回一个对控件的引用。Add方法的语法为:Object.Add(ProgID,Name,Container)其中Object为要添加元素的集合,ProgID为标示的字符串.可通过对象浏览器来确定,例如,CommandButton控件的ProgID是VB.CommandButton. Name是控件的名称. Container是包含添加控件的容器,可以为form或Frame控件等等。        Option Explicit    '通过使用WithEvents关键字声明一个对象变量为新的命令按钮        Private WithEvents NewButton As CommandButton        '增加控件        Private Sub Command1_Click()        If NewButton Is Nothing Then        '增加新的按钮cmdNew        Set NewButton = Controls.Add("VB.CommandButton", "cmdNew", Me)        '确定新增按钮cmdNew的位置        NewButton.Move Command1.Left + Command1.Width + 240, Command1.Top        NewButton.Caption = "新增的按钮"        NewButton.Visible = True        End If        End Sub        '新增控件的单击事件Private Sub NewButton_Click()        MsgBox "您选中的是动态增加的按钮!"End Sub