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:
1 protected void Page_Load( object sender, EventArgs e )
2 {
3 DrawButtons();
4 }
5
6 private void DrawButtons()
7 {
8 Button button;
9
10 for ( int i = 1; i <= 10; i++ )
11 {
12 button = new Button();
13 button.Text = "Button " + i.ToString();
14 button.CommandArgument = i.ToString();
15 button.Click += new EventHandler( button_Click );
16 placeHolder.Controls.Add( button );
17 }
18 }
19
20 void button_Click( object sender, EventArgs e )
21 {
22 Button button = sender as Button;
23
24 if ( button != null )
25 label.Text = "Button " + button.CommandArgument + " was clicked";
26 }
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:
1 Dim WithEvents userButton As Button
2
3 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
4
5 DrawButtons()
6
7 End Sub
8
9 Private Sub DrawButtons()
10
11 For i As Integer = 1 To 10
12 userButton = New Button
13 AddHandler userButton.Click, AddressOf userButton_Click
14 userButton.Text = "Button " + i.ToString()
15 userButton.CommandArgument = i.ToString()
16 placeholder.Controls.Add(userButton)
17 Next
18
19 End Sub
20
21 Protected Sub userButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles userButton.Click
22
23 Dim clickedButton As Button
24
25 If TypeOf sender Is Button Then
26 clickedButton = DirectCast(sender, Button)
27 label.Text = "Button " + clickedButton.CommandArgument + " clicked"
28 End If
29
30 End Sub
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