简体   繁体   中英

Visual Studio 2010 - C# UserControl event firing

I'm attempting to make a grid based dungeon system at the moment in Visual Studio 2010. I have a main user control which contains 64 other smaller user control objects, which I've called GridSquares, organised into an 8x8 grid. The idea behind the grid squares is to act as potential movement spaces within the 'dungeon'. The problem I have at the moment is that I need to be able to call a click event on the user controls (GridSquares) themselves, which have been placed on screen so I can retrieve their coordinate (name) for comparison. However the event does not work when I call it (through clicking).

I am aware that the events work when I place them within the usercontrol (GridSquare object) but I need the click even to work when the user control itself is clicked.

Given that all 64 objects placed are the same type I can not work within the GridSquare class as I require the name of the user control to be returned through the event.

I hope this makes sense but please ask if I need to explain further.

Many thanks, Liam

EDIT: I'm not sure how much this will help or what code to display but the GridSpace controls have already been added to the 'dungeon' user control. Then within I add all 64 to a dictionary:

gridSpaces.Add(gs11.Name, gs11);

Where gs11 is the name of the GridSquare.

From here I tried creating event handlers for the individual user controls on the dungeon screen, which failed to call.

You can use the same handler for each GridSquare and use the sender parameter to decide which one was clicked:

protected void Page_Load(object sender, EventArgs e)
{
   for (int i = 0; i < 64; i++)
   {
      GridSquare square = new GridSquare();
      square.Click += new EventHandler(gridSquare_Click);
      grid.Add(gridSquare);
   }
}

void gridSquare_Click(object sender, EventArgs e)
{
   GridSquare square = (GridSquare)sender;
   // do something cool with the clicked square here
}

I think i get what your saying. Add this code to your user control:

public new event EventHandler Click {
    Add {
        base.Click += value;
        foreach(Control i in Controls) {
            i.Click+=value;
        }
    }
    remove {
        base.Click -= value;
        foreach(Control i in Controls) {
            i.Click -= value;
        }
    }
    }

this will add the click event to everything in your user control, i hope i didnt make any errors, and that this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM