我有这段代码:
DataTable characterDataTable = character.getAllCharacters();
foreach(DataRow row in characterDataTable.Rows)
{
Button button = new Button();
button.Text = row["character"].ToString();
button.ID = row["character"].ToString() + "_btn";
button.Click = "character_btn_Click";
}
characterDataTable
返回包含character
和id
列的3行,例如char1
,char2
和char3
。现在我正在尝试根据检索的行数创建按钮,然后尝试为按钮设置一个值,这样当单击按钮时它将检索值..我希望将值设置为{{1行...
这就是我现在所拥有的:
ID
有没有人知道如何在ASP.NET按钮中存储值并在单击它时检索它?
答案 0 :(得分:2)
要向Button
添加点击处理程序,您应该这样做:
button.Click += character_btn_Click;
您可以使用CommandName
将“值”传递给事件处理程序。所以代码变成了:
DataTable characterDataTable = character.getAllCharacters();
foreach(DataRow row in characterDataTable.Rows)
{
Button button = new Button();
button.Text = row["character"].ToString();
button.ID = row["character"].ToString() + "_btn";
button.CommandName = row["id"].ToString();
button.Click += character_btn_Click;
}
然后点击处理程序:
void character_btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string value = btn.CommandName;
}