2

I have some strings that I have drawn using DrawString

        for (int j = 0; j < dt.Rows.Count; j++)
        {
            e.Graphics.DrawString(Convert.ToString(dt.Rows[j]["ID"]), drawFont, drawBrush, new Point(Convert.ToInt32(dt.Rows[j]["XCord"]), Convert.ToInt32(dt.Rows[j]["YCord"])));
        }

Is there any way to create an onclick event for each drawstring? I was hoping to create a new form when you clicked on the drawstring. Thanks!

Badmiral
  • 1,549
  • 3
  • 35
  • 74
  • 3
    Why aren't you using, for example, buttons? They have a built-in onclick capability, can be given any label text, and can be absolutely positioned anywhere on a form. – mellamokb Jul 13 '12 at 14:23
  • No, there is not an "automatic" way. You have to handle MouseDown event to check if user clicks a string (use MeasureString instead of DrawString). With this you'll just check if the user clicks the bounding box of the string, if you need something less raw then you have to use a GraphicsPath and IsOutlineVisible – Adriano Repetti Jul 13 '12 at 14:26
  • I think he can't use controls because he is drawing a BIG grid of data. – Adriano Repetti Jul 13 '12 at 14:27
  • Use ListBox or ListView or DataGridView to display the strings. – Hans Passant Jul 13 '12 at 15:17

2 Answers2

1

No. When you render things with Graphics you can not bind events to the drawn object.

There are two solutions, you could catch mouse clicks on the form (MouseClick event) and determine if the mouse is over a rendered string (getting the render area using MeasureString). This, however, is unnecessarily difficult and complex.

Instead, I recommended spawning a control dynamically on the form. You could spawn a Button or, if you like the style of just the text on the form, a Label and then bind an EventHandler to their MouseClick event.

Matt Razza
  • 3,524
  • 2
  • 25
  • 29
1

Handle the MouseClick event of the container and enumerate through the rows to find out the "rectangle" of the text and see if the mouse location is inside it:

void panel1_MouseClick(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    foreach (DataRow dr in dt.Rows) {
      Point p = new Point(Convert.ToInt32(dr["XCord"]), Convert.ToInt32(dr["YCord"]));
      Size s = TextRenderer.MeasureText(dr["ID"].ToString(), panel1.Font);
      if (new Rectangle(p, s).Contains(e.Location)) {
        MessageBox.Show("Clicked on " + dr["ID"].ToString());
      }
    }
  }
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225