![](/img/trans.png)
[英]How to trigger click of button that is hidden and has a codebehind event from clientside?
[英]How can i trigger a click event at a Button which has no name
在我的代碼中,按鈕是自動制作的,我需要在點擊事件中保存按鈕的信息。 我正在 WindowsForms 中編寫 ShopSystem 代碼,當我單擊一個按鈕(也應該像單擊 3 次一樣)時,它應該位於下一個表單的文本框中,但我只需要幫助編寫單擊事件的代碼。
while (id < artikelAnzahl)
{
Button ArtikelID = new Button
{
Location = new Point(posX, posY),
Size = new Size(100, 75),
};
posX += 120;
double s = double.Parse(id.ToString()) / 5;
if (int.TryParse(s.ToString(), out int i))
{
posY += 100;
posX = 70;
}
this.Controls.Add(ArtikelID);
foreach (var p in xmlArtikelliste.Descendants("Artikel"))
{
if (int.Parse(p.Attribute("ID").Value) == id)
{
ArtikelID.Text = p.Element("Name").Value + " " +
p.Element("Preis").Value + "€ " +
p.Element("Anzahl").Value + "Stk. ";
}
}
id++;
}
編輯:添加 Click 事件委托不會起作用,因為按鈕是在while loop
中生成的while loop
並且事件處理程序的操作將始終具有上次循環迭代的值。
因此,您可以通過以下方式實現您的需求:
如果您願意,您可以存儲來自 xmlArtikelliste.Descendants("Artikel") 或整篇文章的文章 ID:
ArtikelID.Tag = p.Attribute("ID")
示例代碼:
ArtikelID.Click += (sender, e) =>
{
if(sender is Button button)
{
// Pass button.Tag.ToString() as parameter when navigating to the other form;
}
};
您可以在官方文檔中閱讀更多相關信息。
完整代碼:
while (id < artikelAnzahl)
{
Button ArtikelID = new Button
{
Location = new Point(posX, posY),
Size = new Size(100, 75),
};
posX += 120;
double s = double.Parse(id.ToString()) / 5;
if (int.TryParse(s.ToString(), out int i))
{
posY += 100;
posX = 70;
}
this.Controls.Add(ArtikelID);
foreach (var p in xmlArtikelliste.Descendants("Artikel"))
{
if (int.Parse(p.Attribute("ID").Value) == id)
{
ArtikelID.Text = p.Element("Name").Value + " " +
p.Element("Preis").Value + "€ " +
p.Element("Anzahl").Value + "Stk. ";
ArtikelID.Tag = p.Attribute("ID");
}
}
ArtikelID.Click += (sender, e) =>
{
if (sender is Button button && button.Tag != null)
{
// Pass button.Tag.ToString() as parameter when navigating to the other form;
}
};
id++;
}
編輯 1: (sender, e)
是執行Action
事件處理程序的標准委托簽名。
理想情況下,您可以做的是創建一個按鈕列表,添加按鈕模板並將從 xmlArtikell 接收到的數據綁定到它。 您可以查看以下有關 Win Forms 中數據綁定的介紹性教程。
編輯 2:添加了將數據存儲在 Button 的 Tag 屬性中的解決方案,以便稍后在 Click 事件處理程序中使用它。 否則,該操作將始終使用最后一個 while 循環迭代變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.