[英]How do I programmatically add a button to a gridview and assign it to a specific code-behind function?
在運行時我正在創建一個DataTable並使用嵌套的for循環來填充表。 此表我稍后將DataSource指定給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事件之前將Button控件添加到頁面的控件層次結構中。 我通常在Init事件或CreateChildControls方法中執行此操作。
為了解決您的問題,我建議將按鈕添加到模板標記中的所有單元格,並讓它在那里引用事件處理程序。 然后,讓您的RowDataBound方法處理打開或關閉按鈕的可見性。
最簡單的方法是在GridView中添加一列(如果您願意,可以使用按鈕而不是超鏈接):
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="~/pUser.aspx?field={0}" HeaderText="Select" Text="Select" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.