如何以编程方式添加一个按钮到GridView并将其分配给特定的code隐藏功能? [英] How do I programmatically add a button to a gridview and assign it to a specific code-behind function?
问题描述
嘿!
在运行时我创建一个DataTable,并使用嵌套的for循环来填充表。这个表我后来指定为数据源到GridView和我的RowDataBound分配每个单元格的值。我想知道我怎么可以给每一个小区的按钮,并分配一个按钮,一个codebehind功能。我将有12个按键,每一个包含不同的值。我将preFER如果它们都称与某种事件的存储该特定于小区的值相同的功能。
Hey! In runtime I'm creating a DataTable and using nested for-loops to populate the table. This table I later assign as DataSource to a gridview and on RowDataBound I assign the value of each cell. I want to know how I can give each cell a button and assign that button to a codebehind function. I'll have 12 buttons and each one will contain a different value. I would prefer if they all call the same function with some kind of event that stores the cell-specific value.
这是在哪里得到表创建的code:
This is the code where the Table gets created:
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:
I would like to handle the buttonclick with something like this:
protected void DiceButton_Click(int column, int row, int value)
{
//Do whatever
}
有什么建议?
推荐答案
在中标记你的GridView,分配CommandArgument属性要取其(这里我选择当前gridviewrow的指数)在您的按钮内。
On your gridview in markup, assign CommandArgument attribute to whichever you want (here I choose the index of the current gridviewrow) inside the your buttons.
<asp:Button ID="lbnView" runat="server" Text="Button" OnClick="btn_Clicked"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"></asp:Button>
或者在你的code的后面,可以在下方
Or in your code behind, you can create a button like below
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);
}
}
}
然后做出一个事件处理程序像下面
then make an event handler like below
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
}
}
}
这篇关于如何以编程方式添加一个按钮到GridView并将其分配给特定的code隐藏功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!