你好我在网格视图中有这个按钮字段,它执行以下功能。
但如果我将此按钮字段转换为模板字段,则该函数不会执行。
我得到的错误{"输入字符串的格式不正确。"}。
<asp:ButtonField CommandName="Selectagreement" HeaderText="Select" ControlStyle-CssClass="btn btn-primary" Text="select">
<ControlStyle CssClass="btn btn-primary" />
</asp:ButtonField>
protected void gvAgreement_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
string commandName = e.CommandName.ToString().Trim();
GridViewRow row = gvAgreement.Rows[Convert.ToInt32(e.CommandArgument)];
switch (commandName)
{
case "Selectagreement":
Label1.Text = row.Cells[2].Text;
break;
default: break;
}
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
<asp:TemplateField HeaderText="Select" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="Selectagreement" Text="select"></asp:LinkButton>
</ItemTemplate>
<ControlStyle CssClass="btn btn-primary" />
</asp:TemplateField>
答案 0 :(得分:1)
如@Hakunamatata在评论部分所述,CommandArgument
未设置为<ItemTemplate>
下的链接按钮。
但是,如果您刚刚在触发链接按钮的相应行的行索引之后单击您的代码,则可以执行此操作。
protected void gvAgreement_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
string commandName = e.CommandName.ToString().Trim();
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
switch (commandName)
{
case "Selectagreement":
Label1.Text = row.Cells[2].Text;
break;
default: break;
}
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
基本上我换了
GridViewRow row = gvAgreement.Rows[Convert.ToInt32(e.CommandArgument)];
与
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);