Export (0) Print
Expand All

Determining Coordinates in an ImageButton Web Server Control

Visual Studio .NET 2003

You can use an ImageButton Web Server control as an image map — that is, you can capture the precise x and y coordinates where a user clicked within the image. This allows you to perform different tasks based on where the user clicked.

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 Class.
  2. In the control's Click event handler, get the X and Y properties of the event-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 of the user's click. 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.

' Visual Basic
Private 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 ' Display results
End Sub

// C#
private void ImageButton1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
   // Label text
   string msg = "";   
   // X coordinate from click argument
   int x = e.X;   
   // Y coordinate from click argument
   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";
   }
   // Display results.
   Label1.Text = msg;   
}

See Also

Creating Graphical Button Web Server Controls

Show:
© 2014 Microsoft