I have extended the Label
class as follows:
public class MyLabel: Label {
public Button btn;
public string mydata;
}
In my main program, I instantiated a new instance:
MyLabel lbl = new MyLabel();
lbl.mydata = "some data here";
lbl.btn = new Button();
lbl.btn.Click += new EventHandler(button_pressed);
this.Controls.Add(lbl); // Adds the label to the form
this.Controls.Add(lbl.btn); // Adds the button to the form
And I created a method to handle the button click event:
void button_pressed(Object sender, EventArgs e) {
Button btn = (Button)sender;
//Now I have an access to the property within MyLabel instance.
// but how can I access the parent object?
// I need to access the sibling property [mydata] string from here
btn.Siblings["mydata"] = "some other thing" ; //Something like this
MyLabel lbl = btn.ParentObject(); //Or something like this
lbl.mydata = "Some other thing";
}
This looks like WinForms, in which case either a UserControl or extending Button
class might be a good way to go - just maintain a reference to the parent (a bit more complicated with UserControl, you'd need to define the click event on that control, otherwise you're back to "square 1") I like the Tag
property solution as well, although there is an additional cast, and no guarantee of type safety (since Tag
is an object
, it can be anything by the time you try to access it).
However, let's say you're looking for a more general solution; let's also say that the class in question is sealed
, has no Tag
or similar purpose property, and a Controls
collection is not available (or looping through it is not desirable for performance reasons). To my best knowledge, you can't determine parent object; but you can easily provide your own "Controls" style dictionary, mapping the Button
to the parent:
public class MyLabel: Label {
public static Dictionary<Button, MyLabel> ParentMap = new Dictionary<Button, MyLabel>();
public Button btn;
public string mydata;
public void AddToParentMap() => ParentMap[btn] = this;
}
When you're creating an instance of MyLabel
, just call the AddToParentMap()
function (can't be done in constructor
, because this
pointer is not available until the object is created):
MyLabel lbl = new MyLabel();
lbl.AddToParentMap();
You can then just look it up, fast and easy, in your click event:
void button_pressed(Object sender, EventArgs e) {
Button btn = (Button)sender;
var label = MyLabel.ParentMap[btn];
//...
//Your code...
}
Unlike the Tag
solution, type safety is guaranteed - you always know you're accessing a MyLabel
object.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments