如何以编程方式添加一个按钮到GridView并将其分配给特定的代码隐藏功能?
题
在运行时我创建一个数据表,并使用嵌套for循环来填充该表。此表我后来分配作为数据源到一个gridview和上的RowDataBound我分配的每个单元的值。我想知道我怎么可以给每一个小区的按钮,并分配一个按钮,一个代码隐藏功能。我将有12个按键,每一个包含不同的值。如果他们都称有某种事件的存储小区专用值相同的功能,我宁愿。
这是在表被创建的代码:
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)
{
/*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的指数)在你的按钮内。
<asp:Button ID="lbnView" runat="server" Text="Button" OnClick="btn_Clicked"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"></asp:Button>
或者在后面的代码,您可以在下面
创建像一个按钮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事件之前添加按钮控件添加到页面的控件层次结构。我通常它在初始化事件或CreateChildControls方法。
要解决您的问题,我建议在模板标记添加按钮,所有单元格,并将它引用的事件处理程序存在。然后,有你的RowDataBound方法处理翻转打开或关闭按钮的可见性。
做到这仅仅是一个列添加到你的GridView(你可以使用一个按钮,而不是超链接,如果你喜欢)最简单的方法:
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="~/pUser.aspx?field={0}" HeaderText="Select" Text="Select" />
不隶属于 StackOverflow