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!
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());
}
}
}
}