A simple C# question I hope! Add additional properties to Buttons
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 开发者_JS百科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?
For non-strongly-typed information, you can possibly use the Tag property. Otherwise, I think you'd have to subclass.
Derive from Button:
public class MyButton : Button
{
public string ExtraProperty {get;set;}
}
Personally, I think this is bad code. Really bad code.
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
.
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;
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.
Something you would like to do in this case would be to create a custom control. With a custom control, you have more freedom than with the standard control. Not only will you inherit all the functionality from the existing control you are building your custom control on. You will also have the opportunity to add more functionality and properties to your custom control.
Source: Microsoft - Devloper Network. https://msdn.microsoft.com/en-us/library/ff723977(v=expression.40).aspx
精彩评论