What I'm doing - reset user password on imagebutton click.
Done so far - added GridViewCommandEventHandler - it's firing correctly. Using code from MSDN. I'm getting an empty string ("") for my e.CommandArgument, and it's throwing an error when running (can't parse "" to int).
I can see in the debugger there is a 'rowIndex' property being stored (correctly for my click) elsewhere in e, can I access this? I would think MSDN's code would work - is there something else I've done to make this error occur or another way to fix it? Thanks.
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 page code:
<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>
Event add code:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
GridView1.RowCommand += new GridViewCommandEventHandler(this.resetpassword);
}
Either pass the CommandArgument
(assuming you want to pass the primary key field called PK
):
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="ibtnReset"
Text="reset password"
CommandName="resetpass"
CommandArgument='<%# Eval("Pk") %>'
</ItemTemplate>
</asp:TemplateField>
or get the reference of the GridViewRow
via the NamingContainer
of your ImageButton
:
WebControl wc = e.CommandSource as WebControl;
GridViewRow row = wc.NamingContainer as GridViewRow;
String usrname = ((TextBox)row.FindControl("username")).Text;
You can also pass the RowIndex as CommandArgument:
CommandArgument='<%# Container.DataItemIndex %>'
The ButtonField
class automatically populates the CommandArgument
property with the appropriate index value. For other command buttons, you must manually set the CommandArgument
property of the command button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With