在ASP.NET按钮中存储值

时间:2015-08-22 17:32:34

标签: c# asp.net button

我有这段代码:

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返回包含characterid列的3行,例如char1char2char3。现在我正在尝试根据检索的行数创建按钮,然后尝试为按钮设置一个值,这样当单击按钮时它将检索值..我希望将值设置为{{1行...

这就是我现在所拥有的:

ID

有没有人知道如何在ASP.NET按钮中存储值并在单击它时检索它?

1 个答案:

答案 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;
}