Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WindowsForms equivalent for VB6 indexed controls

In VB6 you have the ability to name your controls with an index.

i.e.: cmdStartInterval(1), cmdStartInterval(2), ... .

Then you have a method head like this:

Private Sub cmdStartInterval_Click(Index As Integer)
...
End Sub

Is this also possible in a similary way in C#?

like image 889
Rookian Avatar asked Nov 28 '25 19:11

Rookian


2 Answers

In c# you can assign all buttons to 1 event handle

protected void cmdButtons_Click(object sender, System.EventArgs e)

when a button clicked this event was called and instance of this button passed to this event by sender parameter.

Note (added later)
While the above is a valid answer to a subset of the problem and an excellent workaround if the index itself is not needed, it should be noted that it is not an equivalent of indexed controls, as the title suggests, but an alternative. VB6's indexed controls are technically arrays. Hence an equivalent would be an array in C# which can only be reached through code, not via the designer.

like image 186
MinhNguyen Avatar answered Nov 30 '25 07:11

MinhNguyen


The equivalent is to use arrays of controls. You will have to add the Index in the event manually. If you don't need the index, you can just assign the events to the controls.

A downside is, both for C# and VB.NET: you cannot create indexed controls with the designer, you have to create them by hand.

The upside is: this gives you more freedom.

EDIT:
This is how that looks:

// in your Form_Init:

Button [] buttons = new Button[10];    // create the array of button controls

for(int i = 0; i < buttons.Length; i++)
{

    buttons[i].Click += new EventHandler(btn_Click);
    buttons[i].Tag = i;               // Tag is an object, not a string as it was in VB6

    // a step often forgotten: add them to the form
    this.Controls.Add(buttons[i]);    // don't forget to give it a location and visibility
}

// the event:
void btn_Click(object sender, EventArgs e)
{
    // do your thing here, use the Tag as index:
    int index = (int) ((Button)sender).Tag;
    throw new NotImplementedException();
}

PS: if you use the form designer, each button will have its own name. If you do as another user suggested, i.e., use the same handler for all of them (as you could do in VB6 too), you cannot easily distinguish the controls by index, as you used to do. To overcome this, simply use the Tag field. It's usually better not to use the Name field for this, as this creates a dependency you don't want.

like image 34
Abel Avatar answered Nov 30 '25 08:11

Abel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!