[英]c# Get Location of programmatically added Button on Click
我在不同位置动态创建了许多按钮,每个按钮都应响应同一事件。 由于必须知道我单击了哪个按钮,因此需要单击按钮的位置。 我不能为每个按钮添加不同的EventHandler,它们在30 * 50的网格上生成,这意味着在最坏的情况下,我得到1500个按钮。 有很多按钮。
private void createNewEnt(int ID, Point position, int style)
{
Button b = new Button();
b.Location = getItemGridLoc(position);
b.Text = getInitial(ID);
b.Size = new System.Drawing.Size(21, 21);
b.FlatStyle = FlatStyle.Popup;
b.Click += new EventHandler(bClick);
if (style == 0)
{
b.BackColor = Color.White;
b.ForeColor = Color.Black;
}
else if (style == 1)
{
b.BackColor = Color.Black;
b.ForeColor = Color.White;
}
this.Controls.Add(b);
b.BringToFront();
}
void bClick(object sender, EventArgs e)
{
MessageBox.Show("you clicked on a Button :D");
}
您可以使用事件处理程序的sender
参数并将其强制转换为按钮,然后检索其位置。
void bClick(object sender, EventArgs e)
{
Button cb = (sender as Button);
MessageBox.Show("You clicked on a Button :D!");
MessageBox.Show(String.Format("Location of clicked Button : {0}, {1}.", cb.Location.X, cb.Location.Y)); // This is just for example.
}
同样,您也可以使用Button做其他事情,例如cb
和/或获取其其他属性。
void bClick(object sender, EventArgs e)
{
Button btn1 = (Button)sender;
string buttonID = btn1.ID;
MessageBox.Show("you clicked on a Button :D");
}
这是获取按钮ID和所有其他所需属性的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.