我在做什么 - 在点击图像按钮时重置用户密码。
到目前为止已完成 - 添加了 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
(假设你想传递名为 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
属性。
关于c# - ASP GridView 在单击按钮时获取行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453613/