如何以编程方式将按钮添加到gridview并将其分配给特定的代码隐藏function?

在运行时我正在创建一个DataTable并使用嵌套的for循环来填充表。 此表我稍后将DataSource指定给gridview,并在RowDataBound上指定每个单元格的值。 我想知道如何给每个单元格一个按钮并将该按钮分配给代码隐藏function。 我将有12个按钮,每个按钮将包含不同的值。 如果它们都使用某种存储特定于单元格的值的事件调用相同的函数,我更愿意。

这是创建表的代码:

protected void GridViewDice_RowDataBound(object sender, GridViewRowEventArgs e) { DataTable diceTable = _gm.GetDice(_gameId); for (int i = 0; i  -1) { /*This is where I'd like to add the button*/ //e.Row.Cells[i].Controls.Add(new Button); //e.Row.Cells[i].Controls[0].Text = specific value from below //This is where the specific value gets input e.Row.Cells[i].Text = diceTable.Rows[e.Row.RowIndex][i].ToString(); } } } 

我想用这样的东西处理buttonclick:

 protected void DiceButton_Click(int column, int row, int value) { //Do whatever } 

有什么建议?

在标记的gridview中,将CommandArgument属性分配给按钮内的任何一个(我在这里选择当前gridviewrow的索引)。

   

或者在你的代码后面,你可以创建一个如下所示的按钮

 protected void GridViewDice_RowDataBound(object sender, GridViewRowEventArgs e) { DataTable diceTable = _gm.GetDice(_gameId); for (int i = 0; i < GameRules.ColumnsOfDice; i++) { if(e.Row.RowIndex > -1) { Button btn = new Button(); btn.CommandArgument = diceTable.Rows[e.Row.RowIndex][i].ToString(); btn.Attributes.Add("OnClick", "btn_Clicked"); e.Row.Cells[i].Controls.Add(btn); } } } 

然后创建一个如下所示的事件处理程

 protected void btn_Clicked(object sender, EventAgrs e) { //get your command argument from the button here if (sender is Button) { try { String yourAssignedValue = ((Button)sender).CommandArgument; } catch { //Check for exception } } } 

不幸的是,在那个阶段你无法创建一个新按钮并为其分配事件。 到目前为止,在页面生命周期中,当它触发事件时,它已经构建了它的“已知”控件列表,它将在页面重新加载时跟踪,因此它不会知道触发按钮单击事件代码下次回帖。

为了使ASP.NET能够正确触发事件方法,您需要在页面的Load事件之前将Button控件添加到页面的控件层次结构中。 我通常在Init事件或CreateChildControls方法中执行此操作。

为了解决您的问题,我建议将按钮添加到模板标记中的所有单元格,并让它在那里引用事件处理程序。 然后,让您的RowDataBound方法处理打开或关闭按钮的可见性。

最简单的方法是在GridView中添加一个列(如果愿意,可以使用按钮而不是超链接):