gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:34:42 24 4
gpt4 key购买 nike

在运行时,我正在创建一个 DataTable 并使用嵌套的 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();
}

}
}

我想用这样的方式处理按钮点击:

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
}
}
}

关于c# - 如何以编程方式将按钮添加到 gridview 并将其分配给特定的代码隐藏函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2418379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com