开发者

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开发者_StackOverflow in C#?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜