Partilhar via


How to: Determine Coordinates in an ImageButton Web Server Control

When users click an ImageButton control, a parameter passed to the event handler for the control's Click event includes the coordinates indicating where the user clicked. This allows you to perform different tasks based on where the user clicked.

Note

If you want to define specific areas of an image as regions that users can click, you can also use the ImageMap control.

Coordinate information is sent as part of the event-argument object for the ImageButton control's Click event.

To determine the coordinates where a user clicks

  1. Create an event handler for the ImageButton control's Click event. The event-argument object for the method must be of type ImageClickEventArgs.

  2. In the Click event handler, get the X and Y properties of the ImageClickEventArgs argument object.

    The x and y coordinates are expressed in pixels, where the upper left corner of the image is (0,0).

    The following example shows how you can determine where the user clicked in a graphic that is 100 by 100 pixels. The code gets the x and y coordinates where the user clicked. It then compares them against predetermined values to see if the user clicked in a particular quadrant. The results are displayed in a Label control.

    Protected Sub ImageButton1_Click(ByVal sender As System.Object, _
          ByVal e As System.Web.UI.ImageClickEventArgs) _
          Handles ImageButton1.Click
       Dim msg as String = ""
       Dim x As Integer = e.X
       Dim y As Integer = e.Y
    
       ' The button graphic is assumed to be 100x100 pixels.
       ' This checks coordinates against predetermined values that
       ' make up quadrants of the picture.
       If x >= 50 And y >= 50 Then
          msg = "Southeast"
       ElseIf x >= 50 And y < 50 Then
          msg = "Northeast"
       ElseIf x < 50 And y >= 50 Then
          msg = "Southwest"
       ElseIf x < 50 And y < 50 Then
          msg = "Northwest"
       End If
       Label1.Text = msg
    End Sub
    
    protected void ImageButton1_Click(object sender, 
        System.Web.UI.ImageClickEventArgs e)
    {
        string msg = "";   
        int x = e.X;   
        int y = e.Y;   
    
        // The button graphic is assumed to be 100x100 pixels.
        // This checks coordinates against predetermined values that
        // make up quadrants of the picture.
        if(x >= 50 && y >= 50)
        {
            msg = "Southeast";
        }
        else if(x >=50 && y < 50)
        {
             msg = "Northeast";
        }
        else if(x < 50 && y >= 50)
        {
            msg = "Southwest";
        }
        else if(x < 50 && y < 50)
        {
            msg = "Northwest";
        }
        Label1.Text = msg;
    }
    

See Also

Reference

Button Web Server Controls Overview