I am writing a program code for creating graphs from graph theory.
Clicking on a grid generates a graph node with the corresponding index. Buttons are generated on the right. I want the nodes to be connected by an edge when the button is clicked. For example, when you click on the button on line 1 and column 2, an edge will be drawn connecting circles 1 and 2.
Button generation code
List<Button> btnList = new List<Button>();
for (int z = 1; z <= count; z )
{
for (int x = 1; x <= count; x )
{
Button btn = new Button();
btn.Text = 0.ToString();
btn.Location = new Point(z*30, x*30);
btn.Size = new System.Drawing.Size(30, 30);
btn.BackColor = System.Drawing.Color.White;
btn.MouseClick = new System.Windows.Forms.MouseEventHandler(btnClick);
panel1.Controls.Add(btn);
btnList.Add(btn);
}
}
The code of the event describing the click of the button
public void btnClick(object sender, EventArgs e)
{
Button button = (Button)sender;
button.Text = (int.Parse(button.Text) 1).ToString();
Graphics g = Graphics.FromImage(bmp);
Pen pen = new Pen(Color.Black);
//g.DrawLine(pen, );
pictureBox1.Image = bmp;
}
Maybe the question is very stupid, but I do not understand how to refer to the indexes of the pressed button in the btnClick function.
CodePudding user response:
You have, for every object in C#, a Tag property which is free. You can use it to store the coordinates of your button.
So, insert before you add the btn to the panel1.Controls, something like:
btn.Tag = new Point(z, x);
Then, in the btnClick delegate, to get back your coordinates, you use something like:
Button button = sender as Button;
Point p = button.Tag;
int z = p.X;
int x = p.Y;
You can keep the Button button = (Button)sender; The only difference is that casting can throw an exception but the keyword 'as' can't.
As I am writing this, I see the new comments and your reply. Tag isn't in the delegates like KeyDown but with the properties like Location, Size, Text, etc.
CodePudding user response:
You already store z and x:
btn.Location = new Point(z*30, x*30);
You can do this in the click handler to retrieve them:
int z = button.Location.X / 30;
int x = button.Location.Y / 30;
CodePudding user response:
Thanks for answers.
I add code when generation buttons
btn.Tag = new Point(z, x);
and i use btn.Tag when click on button
Point p = (Point)button.Tag;
int z = p.X;
int x = p.Y;