ASP.NET rowcommand无法正常工作

问题描述 投票:0回答:2

我用rowcommandrowarguements在同一页面上创建了两个按钮,但是,只有其中一个工作正常,我不知道为什么当我试图点击另一个按钮时出现“意外错误”框。(btnInterview工作正常,btnContact不管用)

不仅提示错误消息,btnContact也无法在rowcommand中触发事件。

下面的代码(.aspx部分):

<asp:GridView ID="GridView2" runat="server" AllowPaging="True"
    EmptyDataText="No Sample is found"
    OnPageIndexChanging="GridView1_PageIndexChanging"
    PageSize="20"
    OnSorting="GridView1_Sorting" OnDataBound="GridView1_DataBound"
    OnRowCommand="GridView1_RowCommand" Width="100%" AllowSorting="True" OnRowCreated="GridView1_RowCreated">
    <RowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
    <Columns>
        <asp:TemplateField HeaderText="Phone Interview">
            <ItemTemplate>
                <asp:Button ID="btninterview" runat="server" Text="Interview" CommandName="btninterview_Click"
                    CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CssClass="intBtn" />
                <asp:HiddenField runat="server" ID="hidid" Value='<%# Bind("Id")%>' />
                <asp:HiddenField runat="server" ID="hidProject" Value='<%# Bind("Project")%>' />
                <asp:HiddenField ID="hidEnablebtn" runat="server" Value='<%# Bind("enableButton")%>' />
            </ItemTemplate>
            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Phone Interview">
            <ItemTemplate>
                <asp:Button ID="btnContact" runat="server" Text="Contact" CommandName="btncontact_Click"
                    CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CssClass="intBtn" />
                <asp:HiddenField ID="hidVisibleBtn" runat="server" Value='<%# Bind("visibleButton")%>' />
            </ItemTemplate>
            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
        </asp:TemplateField>
    </Columns>
</asp:GridView>

下面的代码(c#部分):

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e){
    Button btn = (Button)sender;
    switch (btn.CommandName)
    {
        case "btninterview_Click":
            //do sth1
            break;

        case "btncontact_Click":
            //do sth2
            break;
    }            
}
c# asp.net rowcommand
2个回答
0
投票

您正在使用RowCommand事件。在这种情况下,sender不是Button,而是GridView本身。因此,当您尝试将GridView转换为Button时,您将获得Cast exeptions。你应该铸造CommandSource

Button btn = e.CommandSource as Button;

0
投票

我希望你可以直接从GridViewCommandEventArgs本身获取命令名,如下所示,

switch (**e.CommandName**)
{
    case "btninterview_Click":
        //do sth1
        break;

    case "btncontact_Click":
        //do sth2
        break;
}

REF:GridViewCommandEventArgs

希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.