[英]Highlighting a row in asp.net gridview on click of template button
[英]ASP GridView get row values on button click
我在做什么 - 在圖像按鈕上單擊重置用戶密碼。
完成到目前為止 - 添加了GridViewCommandEventHandler - 它正確觸發。 使用MSDN中的代碼。 我的e.CommandArgument得到一個空字符串(“”),它在運行時拋出錯誤(無法解析“”到int)。
我可以在調試器中看到在e的其他地方存儲了一個'rowIndex'屬性(正確地為我的點擊),我可以訪問它嗎? 我認為MSDN的代碼會起作用 - 是否還有其他一些方法可以解決這個錯誤或者其他方法來修復它? 謝謝。
void resetpassword(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField columns are used, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "resetpass")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection. Use the
// CommandSource property to access the GridView control.
GridView GridView1 = (GridView)e.CommandSource;
GridViewRow row = GridView1.Rows[index];
String usrname = row.FindControl("username").ToString();
aspx頁面代碼:
<asp:TemplateField HeaderText="Reset Password">
<ItemTemplate>
<asp:ImageButton ID="ibtnReset" runat="server" CausesValidation="false"
CommandName="resetpass" ImageUrl="~/Images/glyphicons_044_keys.png" Text="Button" />
</ItemTemplate>
<HeaderStyle Width="70px" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
活動添加代碼:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
GridView1.RowCommand += new GridViewCommandEventHandler(this.resetpassword);
}
我認為你缺少CommandArgument='<%# Container.DataItemIndex %>'
為了你的代碼。
<asp:ImageButton ID="ibtnReset" runat="server" CausesValidation="false"
CommandArgument='<%# Container.DataItemIndex %>'
CommandName="resetpass" ImageUrl="~/Images/glyphicons_044_keys.png"
Text="Button" />
這是一個關於SO ASP.NET GridView RowIndex As CommandArgument的問題,供進一步閱讀。
ButtonField類使用適當的索引值自動填充CommandArgument屬性。
傳遞CommandArgument
(假設您要傳遞名為PK
的主鍵字段):
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="ibtnReset"
Text="reset password"
CommandName="resetpass"
CommandArgument='<%# Eval("Pk") %>'
</ItemTemplate>
</asp:TemplateField>
或者通過ImageButton
的NamingContainer
獲取GridViewRow
的引用:
WebControl wc = e.CommandSource as WebControl;
GridViewRow row = wc.NamingContainer as GridViewRow;
String usrname = ((TextBox)row.FindControl("username")).Text;
您還可以將RowIndex作為CommandArgument傳遞:
CommandArgument='<%# Container.DataItemIndex %>'
ButtonField
類使用適當的索引值自動填充CommandArgument
屬性。 對於其他命令按鈕,您必須手動設置命令按鈕的CommandArgument
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.