2

I have the following problem:

I want to access a variable inside my class through a mouse-click.

My Class:

public class Box
{

    public Label LabelDown = new Label();
    public byte SavedID;

    public Box(EventHandler InsideEvent)
    {

        LabelDown.Text = null;
        LabelDown.Size = new Size(96, 32);
        LabelDown.Visible = true;
        LabelDown.Click += new EventHandler(InsideEvent);

        SavedID = 0;

    }
}

Now, I created an Array of this class in a Form, using:

 Box[] myBox = new Box[5];

In the code for initializing my Form, I've added this:

  for (byte j = 0; j <= myBox.Length(); j++)
     {
         mybox = new Box(Box_goInside_Click)
         Controls.Add(Box[j].LabelDown);
     }

now the Click event handler is:

   void Box_goInside_Click(object sender, EventArgs e)
     {

        //here i want to access the saved ID of MyBox that uses this Label
        Dosomething( whatever comes here. SavedID)

     }

I hope you understand what my problem is... if I use base, or anything else, it will get to Object, because it sees only my Label, but not that its part of my class Box.

lhan
  • 4,585
  • 11
  • 60
  • 105

1 Answers1

1

You have few options:

  • put a reference of each Box inside the Tag property of each Label.
  • handle the event Click event inside the Box class and then call the handler replacing the original sender (Label) with the Box itself.

First solution:

public Box(EventHandler InsideEvent)
{
    LabelDown.Text = null;
    LabelDown.Size = new Size(96, 32);
    LabelDown.Visible = true;
    LabelDown.Click += new EventHandler(InsideEvent);
    LabelDown.Tag = this;

    SavedID = 0;
}

void Box_goInside_Click(object sender, EventArgs e)
{
    Box box = (Box)((Control)sender).Tag;

    // Do your stuff
}

Second solution:

public class Box
{
    public Label LabelDown = new Label();
    public byte SavedID;

    public Box(EventHandler InsideEvent)
    {

        LabelDown.Text = null;
        LabelDown.Size = new Size(96, 32);
        LabelDown.Visible = true;
        LabelDown.Click += OnLabelClick;

        SavedID = 0;

        _insideEvent = InsideEvent;
    }

    private EventHandler _insideEvent;

    private OnLabelClick(object sender, EventArgs e)
    {
        if (_insideEvent != null)
            _insideEvent(this, e);
    }
}

void Box_goInside_Click(object sender, EventArgs e)
{
    Box box = (Box)sender;

    // Do your stuff
}
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208