简体   繁体   中英

How can i get number of PictureBox that was clicked?

I make Tic Tac Toe game, i have 9 cells that the player can click. Initially cell don't have any picture, but when cell was clicked it's picture must changes. How can i create this event for every cell without code duplicate?

The signature for a click event has a "sender" object. You can use that for reference. Cast it to the appropriate type, and you can access all its public properties directly.

You should be able to do something like:

protected void pictureClick(Object sender, EventArgs e) {
    PictureBox pic = sender as PictureBox;

    if (pic != null) {
        // set the image based on which players turn it is.
    } 
}

and now each picture box would have its onClick event set to this one pictureClick function.

--- Edit ---

I'd also add that using independent UI controls in this manner is extremely inefficient for large tile games. For a 3x3 tic-tac-toe grid, it's probably fine, but for something like a 8x8 chessboard, the refresh times for all 64 squares is going to be noticeable, because every UI component on the page has its Paint() method called when the window refreshes. I'm speaking from experience here. I once tried to use this approach of having a grid of 10x10 Panel components with custom draw methods based on the game state data, and anytime the window was resized, the game would hang for several seconds while everything would refresh.

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