views:

55

answers:

5

hi on a windows form (not WPF) I dynamically create buttons on a flowlayout and I would like to add some properties to them simply to store other values (int and string) with the buttons for latter use.

            Button bn = new Button();
            bn.Text = "mybutton";
            bn.Name = "mybutton";
            toolTip1.SetToolTip(bn, "some tip");
            bn.Location = new Point(200, 200);
            bn.Size = new Size(110, 30);
            bn.BackColor = SystemColors.Control;
            bn.Show();
            flowLayoutPanel1.Controls.Add(bn);

I have about 6 values I would like to store with each button as it is different for each button..

Can this be done?

+4  A: 

For non-strongly-typed information, you can possibly use the Tag property. Otherwise, I think you'd have to subclass.

Jason
+1  A: 

Yes. You can assign data like this to the Button.Tag property (inherited from Control). This property is typed as an object so you can assign anything you want to it.

Alternative, you could inherit from Button.

Jason
A: 

Like all WinForms controls, Button also has a Tag property, which can be used to store arbitrary objects.

public struct MyButtonData {
    public int myInt;
    public string myString;
}

...

bn.Tag = new MyButtonData() {myInt = 3, myString = "Hello World"};

...

var data = (MyButtonData)bn.Tag;
Heinzi
+2  A: 

Derive from Button:

public class MyButton : Button
{
  public string ExtraProperty {get;set;}
}

Personally, I think this is bad code. Really bad code.

Femaref
Why? The `MyButton` name (if so, I agree with you there)? Inheritance vs Composition (which is kind of difficult when you don't control the base class)? It would be nice to why you're offering such bad code...
Austin Salonen
a) this is an example b) you can't employ composition here either, because forms wouldn't work then. As it's not completely clear what the OP is trying to achieve I didn't write about splitting GUI and Logic. This way is just a strongly typed way of employing the `Control.Tag` property and can be useful in some instances.
Femaref
A: 

You can either:

  • Create a control, derived from Button, and add the additional properties.
  • Create a class to encapsulate the data you want to assign to the each button, instantiate the class, and then point the control's "Tag" property at the instantiated object.

The Tag property was designed for this very purpose.

Michael