ASP 网格视图在单击按钮时获取行值
本文关键字:获取 按钮 单击 网格 视图 ASP | 更新日期: 2023-09-27 18:33:17
我在做什么 - 在图像按钮单击时重置用户密码。
到目前为止完成 - 添加了 GridViewCommandEventHandler - 它正在正确触发。使用 MSDN 中的代码。我为我的 e.CommandArgument 获取了一个空字符串 ("),并且在运行时抛出错误(无法将 " 解析为 int)。
我可以在调试器中看到有一个"rowIndex"属性被存储(正确用于我的点击)在 e 的其他地方,我可以访问它吗?我认为 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
属性。
我认为你错过了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 作为 CommandArgument 的问题,以供进一步阅读。
类会自动填充 CommandArgument。 具有相应索引值的属性。
这是 MSDN 源代码