Accessing another variable in the same class with a click event

杀马特。学长 韩版系。学妹 提交于 2019-12-12 20:19:10

问题


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.


回答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
}


来源:https://stackoverflow.com/questions/13382688/accessing-another-variable-in-the-same-class-with-a-click-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!