MOHIT VERMA
MOHIT VERMA

Reputation: 53

how to get the object reference of a class which has a label control inside it from that label?

I have a class which has a Label field. Now i want to get the reference of that class from that label. How can i do that? Here is what i have.

public class Abc
{
    Label l;
}
public partial class Form1 : Form
{
    private void btnins_Click(object sender, EventArgs e)
    {
       Abc ob=new Abc();
       ob.l=new new Label();
       l.Text="Right Click Me";
       l.ContextMenuStrip = cntxtdelmnu;
    }


    private void cntxtdelnode_Click(object sender, EventArgs e)
    {
       Label lbl= (Label)cntxtdelmnu.SourceControl;

       //Here I have to get the reference of ob using lbl.
    }
}

Upvotes: 0

Views: 340

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500645

You can't, basically. There could be multiple objects which have references to that label - or none at all. You can't get a "backwards" reference. You could potentially store a reference in the Tag property:

Abc ob=new Abc();
ob.l= new Label();
ob.l.Text="Right Click Me";
ob.l.ContextMenuStrip = cntxtdelmnu;
ob.l.Tag = ob;

Or using an object initializer:

Abc ob = new Abc();
ob.l = new Label { Text = "Right Click Me", ContextMenuStrip = cntxtdelmnu, Tag = ob };

I would try to avoid needing that though. It's not clear from the question why you want it, but there may be better approaches. (I really hope those aren't your real names, too...)

Upvotes: 1

Related Questions