Wednesday, 4 July 2012

Add Controls Run time in VB.NET & C#


hi............
Mostly we make control design time, we handle many event like click, mouseover,moueout etc. This is a easy process for design time because there is not any need to attach event handler visual studio attach necessary code automatically.
You can add control on run time………… for do this you will have to perform following steps
  • Make an object of relevant control
    eg. Button btn =new Button()      [C# ]
          dim btn as new Button()         [VB.NET]
  • After make an object of control you have to manage control property
    eg. Location,size,backcolor,text etc
  • You can also attach events..
Add an Button in C#
  Button btn = new Button();
            btn.Text="Click";
            btn.Location=new Point(100,100);
            btn.Click +=new EventHandler(btn_Click);
            this.Controls.Add(btn);
     following function will catch and handle button click event….
private void btn_Click(object sender,EventArgs e)
        {
            MessageBox.Show("Called");
        }
Add a combo box in vb.net
            Dim com As ComboBox
        com = New ComboBox
        com.Items.Add("one")
        com.Items.Add("two")
        com.Items.Add("three")
        com.Location = New Point(150, 100)
        AddHandler com.SelectedIndexChanged,AddressOf com_click
        Me.Controls.Add(com)
following function will catch and handle combo box
selectindexchange event….
       Private Sub com_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        MsgBox("Called event")
    End Sub