I'm a C# programmer but I am having to do a project in VB.Net and need a bit of help in creating dynamic controls. Below is an example in C# that basically creates 10 buttons and on click a label displays which button has been clicked:
protected void Page_Load( object sender, EventArgs e )
{
DrawButtons();
}
private void DrawButtons()
{
Button button;
for ( int i = 1; i <= 10; i++ )
{
button = new Button();
button.Text = "Button " + i.ToString();
button.CommandArgument = i.ToString();
button.Click += new EventHandler( button_Click );
placeHolder.Controls.Add( button );
}
}
void button_Click( object sender, EventArgs e )
{
Button button = sender as Button;
if ( button != null )
label.Text = "Button " + button.CommandArgument + " was clicked";
}
Now I have tried to write the same simple bit of code in VB.Net (see below) however I can't seem to do it without creating a global variable of type button with the "WithEvents" attribute:
Dim WithEvents userButton As Button
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
DrawButtons()
End Sub
Private Sub DrawButtons()
For i As Integer = 1 To 10
userButton = New Button
AddHandler userButton.Click, AddressOf userButton_Click
userButton.Text = "Button " + i.ToString()
userButton.CommandArgument = i.ToString()
placeholder.Controls.Add(userButton)
Next
End Sub
Protected Sub userButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles userButton.Click
Dim clickedButton As Button
If TypeOf sender Is Button Then
clickedButton = DirectCast(sender, Button)
label.Text = "Button " + clickedButton.CommandArgument + " clicked"End If
End Sub
Is what I have done the right way of doing this or is there a more efficient way?
accyboy1981
Member
24 Points
25 Posts
C# to VB Dynamically Creating Controls
Feb 21, 2008 08:49 PM|LINK
Hi,
I'm a C# programmer but I am having to do a project in VB.Net and need a bit of help in creating dynamic controls. Below is an example in C# that basically creates 10 buttons and on click a label displays which button has been clicked:
protected void Page_Load( object sender, EventArgs e ) { DrawButtons(); } private void DrawButtons() { Button button; for ( int i = 1; i <= 10; i++ ) { button = new Button(); button.Text = "Button " + i.ToString(); button.CommandArgument = i.ToString(); button.Click += new EventHandler( button_Click ); placeHolder.Controls.Add( button ); } } void button_Click( object sender, EventArgs e ) { Button button = sender as Button; if ( button != null ) label.Text = "Button " + button.CommandArgument + " was clicked"; }Now I have tried to write the same simple bit of code in VB.Net (see below) however I can't seem to do it without creating a global variable of type button with the "WithEvents" attribute:
Is what I have done the right way of doing this or is there a more efficient way?
Thanks for your help in advance.
Simon
dynamic controls asp.net.c# Dynamic asp.net2.0 asp.net vb