[英]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.