如何通过按钮点击传递参数

3

我有一个带有数据绑定的网格视图:所有行都是根据ItemSource生成的。我还在末尾添加了一个包含按钮的列。如何将当前itemSource中的字段绑定为按钮单击事件的参数?

以下是代码示例:

WEBFORM

<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="false" 
    ItemType="ServiceMonitoring.MyClass" 
    SelectMethod="GetMyClassItems" 
    CellPadding="4" 
    ShowFooter="true">
    <Columns>
        <asp:BoundField DataField="MyProperty" HeaderText="ID" />
        <asp:TemplateField HeaderText="Action">
            <ItemTemplate>
                <asp:Button runat="server" 
                    CommandArgument='<%= MyClass.MyProperty %>' 
                    CommandName="ThisBtnClick" 
                    OnClick="Unnamed_Click" 
                    Text="retraiter !" />
                <%--<button onclick="UpdateMyClassItems" runat="server" value="VALEUR">retraiter !</button>--%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

代码后台

public partial class WebForm1: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) { }

    public List<MyClass> GetMyClassItems()
    {
        var a = new MyClass() { MyProperty = 2 };
        return new List<MyClass>() { a };
    }

    protected void Unnamed_Click(object sender, EventArgs e)
    {
        var arg = (sender as Button).CommandArgument;
        string ID = arg.ToString();
    }
}

public class MyClass
{
    public int MyProperty { get; set; }
}

命令参数绑定无法正常工作。请问你能帮忙吗?

@Aristos,我现在遇到了这个错误:编译器错误消息:CS0103:在当前上下文中找不到名称 'MyClass'(The name 'MyClass' doesn't exist in the current context)。你能帮我吗? - Guillaume P.
error in English please - naveen
@naveen 当前上下文中不存在'MyClass'这个名称。 - Guillaume P.
1个回答

2

CommandArgument更改为以下内容。

CommandArgument='<%# Eval("MyProperty") %>'

没问题。您已经提到了ItemType="ServiceMonitoring.MyClass"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接