Advertisement
ASP_Volume3 Windows CE #58173

Adding controls withevents at runtime in VB .NET

Sometimes it is necessary to add controls at runtime or use a dynamic array of controls and you want to have events too , this tutorial will show you how to do this.

AI

Riepilogo AI: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Codice sorgente
original-source
<p><h5>Adding controls at runtime</h5></p>
<p>
First of all you need to declare an array of that control but you can't do that by the withevents statement so you first need to create a class that has the events in itself then you delare an array of that class. in the examples below i will make a program with a button that when it is pressed it will add a textbox to the form in a random location. here's the definition of the class:<br>
(in this example only the TextChanged event is rewritten but you can do it with all the events)<br><h4><pre>
Public Class MyTextBox 
  Inherits System.Windows.Forms.TextBox 
  Private Sub MyTextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.TextChanged 
  MsgBox(Me.Name & "'s text changed!") 
  End Sub
End Class</pre></h4>
Then you declare an array of this class in the Form class like this:<br><br>
<h4>Private TextBoxes() as MyTextBox</h4><br><br>
then assuming that you have a Button with the name of 'Button1' you write the following code in the Clicked event:<br><br>
<h4><pre>
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Static num As Integer
  num += 1
  ReDim TextBoxes(num)
  TextBoxes(num - 1) = New MyTextBox()
  With TextBoxes(num - 1)
   .Name = "Textbox" & num
   .Text = "Textbox" & num
   .Location = New System.Drawing.Point(10, num * (.Height + 10))
  End With<br>
  Me.Controls.AddRange(New System.Windows.Forms.Control() {TextBoxes(num - 1)})
 End Sub
End Class </pre></h4>
then TextBox appears on the form , so that's it.
</p>
Commenti originali (3)
Recuperato da Wayback Machine