Free Blog Counter

Ranjiths Dot Net Blog: Create and Remove Controls at Run Time

Friday, 3 October 2008

Create and Remove Controls at Run Time

It is always been very interesting to work with Visual Studio 2005 and 2008.  I love programming with VB.Net and it is somewhat amazing.  

When I started developing applications with Visual Studio 2008, I faced some difficulties in handling the controls which are created at runtime.  

The code below shows the creation of the label at runtime and I believe it is easy to follow without any explanation:

 

Imports System.Windows.Forms

Public Class Form1

    Dim i As Integer

‘This part of the code is to create label at runtime

‘---------------------------------------------------------------------

 Private Sub Button1_Click(ByVal sender As System.Object, 

                           ByVal e As System.EventArgs) Handles Button1.Click

        Dim alabel As New Label

        Me.Controls.Add(alabel)

        alabel.Top = Me.Controls.Count * 25

        alabel.BackColor = Color.CornflowerBlue

        alabel.Width = 100

        i += 1

        alabel.Text = "Label" & i

        alabel.Tag = "Label" & i

 End Sub

 

‘---------------------------------------------------------------------

‘This part of the code is to remove the label

    Private Sub Button2_Click(ByVal sender As System.Object, 

                              ByVal e As System.EventArgs) Handles Button2.Click

        Dim ctrl As Control

        For Each ctrl In Controls

            If TypeOf ctrl Is Label Then

                If ctrl.Tag = "Label" & i Then

                    Me.Controls.Remove(ctrl)

                    i = i - 1

                End If

            End If

        Next

    End Sub

End Class

No comments: