ASP.Net嵌套GridView OnRowCommand没有触发

时间:2016-08-27 00:51:56

标签: asp.net gridview rowcommand

我已经尝试过我在这里和其他地方找到的所有建议。我为页面设置了EnableViewState为true和false。我为网格设置了EnableViewState为true和false。我已经尝试在父网格RowCreated中注册子网格的事件。我真的很茫然。我该如何工作?父母或儿童事件都没有被解雇。

<%@ Control Language="C#" EnableViewState="False" AutoEventWireup="False" CodeBehind="View.ascx.cs" Inherits="IMS.Modules.CreateMerchandise.View" %>


<asp:GridView ID="gvVariants"
              runat="server"
              AutoGenerateColumns="False"
              CssClass="Grid"
              DataKeyNames="ID"
              OnRowDataBound="gvVariants_OnRowDataBound"
              ShowFooter="True"
              EnableViewState="False"
              OnRowCreated="gvVariants_OnRowCreated"
              OnRowCommand="gvVariants_OnRowCommand">
    <Columns>
        <asp:TemplateField InsertVisible="False">
            <ItemStyle HorizontalAlign="Center" Width="30"/>
            <ItemTemplate>
                <img alt="" style="cursor: pointer; height: 20px; width: 20px;" src="../images/ManageMerchandise/plus.png"/>
                <asp:Panel ID="pnlValues" runat="server" Style="display: none" EnableViewState="False">
                    <asp:GridView
                        ID="gvValues"
                        runat="server"
                        AutoGenerateColumns="False"
                        CssClass="ChildGrid"
                        DataKeyNames="ID"
                        ShowFooter="True"
                        EnableViewState="False"
                        OnRowCommand="gvValues_OnRowCommand">
                        <Columns>
                            <asp:TemplateField ItemStyle-Width="15px">
                                <FooterTemplate>
                                    <asp:Button runat="server" text="Add" ID="btnAddValue" CommandName="AddValue" CommandArgument='<%# Bind("ID") %>'/>
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField
                                HeaderText="Value"
                                InsertVisible="True"
                                ItemStyle-Width="150px">
                                <ItemTemplate>
                                    <asp:Label ID="lblValue" runat="server"
                                               Text='<%# Bind("VariantValue") %>'>
                                    </asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:TextBox ID="NewValue" runat="server" Width="150"></asp:TextBox>
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Use">
                                <ItemTemplate>
                                    <asp:CheckBox ID="cbUseVariantValue" runat="server"
                                                  Enabled="true"/>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:CheckBox ID="cbUseNewVariantValue" runat="server"/>
                                </FooterTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </asp:Panel>
            </ItemTemplate>
            <FooterTemplate>
                <asp:Button runat="server" text="Add" ID="btnAddVariant" CommandName="addVariant" CommandArgument='<%# Bind("ID") %>'/>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Variant" InsertVisible="True">
            <ItemTemplate>
                <asp:Label ID="lblVarietal" runat="server"
                           Text='<%# Bind("Name") %>'>
                </asp:Label>
            </ItemTemplate>
            <ItemStyle HorizontalAlign="Center" Width="240"/>
            <FooterTemplate>
                <asp:TextBox ID="NewVariant" runat="server"></asp:TextBox>
            </FooterTemplate>
            <FooterStyle Wrap="False"/>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Use">
            <ItemTemplate>
                <asp:CheckBox ID="cbUseVariant" runat="server"
                              Enabled="true"/>
            </ItemTemplate>
            <FooterTemplate>
                <asp:CheckBox ID="cbUseNewVariant" runat="server"/>
            </FooterTemplate>
            <ItemStyle HorizontalAlign="Center"/>
            <FooterStyle HorizontalAlign="Center"/>
        </asp:TemplateField>
    </Columns>
</asp:GridView>OnLoad:

的OnLoad:

protected override void OnLoad(EventArgs e)
{
        try
        {
            base.OnLoad(e);
            if (!IsPostBack)
            {
                gvVariants.DataSource = GetVariantTable();
                gvVariants.DataBind();
            }
        }
        catch (Exception exc) //Module failed to load
        {
            DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
        }

    }

代码隐藏中的RowDataBound:

    protected void gvVariants_OnRowDataBound(Object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {         
            String variantId= gvVariants.DataKeys[e.Row.RowIndex].Value.ToString();

            GridView gvValues = e.Row.FindControl("gvValues") as GridView;
            using (var ipv = new IMM_ProductVariantValuesController())
            {
                ipv.Gets(variantId,"IMM_ProductVariants_ID",pWhere: $"and (portal_id=-1 or portal_id={PortalId})");
                ipv.LoadDatatable();
                gvValues.DataSource = ipv.Datatable;
                gvValues.DataBind();
            }
        }      
    }

    protected void gvVariants_OnRowCommand(Object sender, GridViewCommandEventArgs e)
    {
        Response.Write("got here");
        Response.End();
    }

2 个答案:

答案 0 :(得分:0)

有几个问题会导致问题。

“添加”按钮有onClick个事件,但您也在每个网格中使用onRowCommand。单击“添加”按钮时会触发三个事件(按钮单击,父网格行命令,嵌套网格行命令)。

看起来您正在使用全局变量VariantID。这适用于CommandArgument,但是如果您在页面的HTML中使用它,它仍然只包含最后添加的行的ID值。所以它有效,但不推荐。更好地使用像CommandArgument='<%# Bind("itemID") %>'

这样的东西

您使用“添加”按钮中VariantID属性中的CommandArgument错误。您使用CommandArgument="<%=VariantID%>",因此命令参数是字符串<%=VariantID%>。您可以像CommandArgument='<%# VariantID %>'

一样使用它

您正在OnLoad(EventArgs e)上的try-catch块之外绑定网格。当出现错误时,它将使整个DotNetNuke页面崩溃,而不是触发ModuleLoadException。虽然这可以用于测试目的。

首先修复这些问题并查看是否有帮助。它在我的开发服务器上完成。

答案 1 :(得分:0)

这现在有效:

<%@ Control Language="C#" EnableViewState="False" ViewStateMode="Disabled" AutoEventWireup="False" CodeBehind="View.ascx.cs" Inherits="IMS.Modules.CreateMerchandise.View" %>

<style type="text/css">
    body {
        font-family: Arial;
        font-size: 10pt;
    }

    .Grid td {
        background-color: #A1DCF2;
        color: black;
        font-size: 10pt;
        line-height: 200%
    }

    .Grid th {
        background-color: #3AC0F2;
        color: White;
        font-size: 10pt;
        line-height: 200%
    }

    .ChildGrid td {
        background-color: #eee !important;
        color: black;
        font-size: 10pt;
        line-height: 200%
    }

    .ChildGrid th {
        background-color: #6C6C6C !important;
        color: White;
        font-size: 10pt;
        line-height: 200%
    }
</style>


<script type="text/javascript">

    function SetID(id) {
        document.getElementById("hfVariantID").value = id;
    }

    $("[src*=plus]")
        .live("click",
            function() {
                $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>");
                $(this).attr("src", "../images/ManageMerchandise/minus.png");
            });
    $("[src*=minus]")
        .live("click",
            function() {
                $(this).attr("src", "../images/ManageMerchandise/plus.png");
                $(this).closest("tr").next().remove();
            });
</script>
<asp:UpdatePanel runat="server" ID="upVariants" UpdateMode="Conditional" ViewStateMode="Disabled" EnableViewState="False">
<ContentTemplate>
<asp:GridView ID="gvVariants" runat="server" AutoGenerateColumns="False" CssClass="Grid" DataKeyNames="ID" OnRowDataBound="gvVariants_OnRowDataBound" ShowFooter="True" EnableViewState="False" OnRowCommand="gvVariants_OnRowCommand">
    <Columns>
        <asp:TemplateField InsertVisible="False">
            <ItemStyle HorizontalAlign="Center" Width="30"/>
            <ItemTemplate>
                <img alt="" style="cursor: pointer; height: 20px; width: 20px;" src="../images/ManageMerchandise/plus.png"/>
                <asp:Panel ID="pnlValues"  runat="server" Style="display: none" EnableViewState="False">
                    <asp:GridView ID="gvValues" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvValues_OnRowDataBound" CssClass="ChildGrid" DataKeyNames="ID" ShowFooter="True" EnableViewState="False">
                        <Columns>
                            <asp:BoundField DataField="ID" Visible="False"/>
                            <asp:TemplateField ItemStyle-Width="15px">
                                <FooterTemplate>
                                    <asp:Button runat="server" text="Add" ID="btnAddValue" OnClick="btnAddValue_Click" CommandName="AddValue" CommandArgument='<%# Bind("ID") %>'/>
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField
                                HeaderText="Value"
                                InsertVisible="True"
                                ItemStyle-Width="150px">
                                <ItemTemplate>
                                    <asp:Label ID="lblValue" runat="server"
                                               Text='<%# Bind("VariantValue") %>'>
                                    </asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:TextBox ID="NewValue" runat="server" Width="150"></asp:TextBox>
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Use">
                                <ItemTemplate>
                                    <asp:CheckBox ID="cbUseVariantValue" runat="server"
                                                  Enabled="true"/>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:CheckBox ID="cbUseNewVariantValue" runat="server"/>
                                </FooterTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </asp:Panel>
            </ItemTemplate>
            <FooterTemplate>
                <asp:Button runat="server"  text="Add"  ID="btnAddVariant" CommandName="addVariant" OnClick="btnAddVariant_Click" CommandArgument='<%# Bind("ID") %>'/>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Variant">
            <ItemTemplate>
                <asp:Label ID="lblVarietal" runat="server"
                           Text='<%# Bind("Name") %>'>
                </asp:Label>
            </ItemTemplate>
            <ItemStyle HorizontalAlign="Center" Width="240"/>
            <FooterTemplate>
                <asp:TextBox ID="NewVariant" runat="server"></asp:TextBox>
            </FooterTemplate>
            <FooterStyle Wrap="False"/>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Use">
            <ItemTemplate>
                <asp:CheckBox ID="cbUseVariant" runat="server"
                              Enabled="true"/>
            </ItemTemplate>
            <FooterTemplate>
                <asp:CheckBox ID="cbUseNewVariant" runat="server"/>
            </FooterTemplate>
            <ItemStyle HorizontalAlign="Center"/>
            <FooterStyle HorizontalAlign="Center"/>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:HiddenField runat="server" ID="hfVariantID" ClientIDMode="Static"/>

代码隐藏:

/*
' Copyright (c) 2016  Indy Music Systems
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
*/

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using IMS.Model;

namespace IMS.Modules.CreateMerchandise
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    ///     The View class displays the content
    ///     Typically your view control would be used to display content or functionality in your module.
    ///     View may be the only control you have in your project depending on the complexity of your module
    ///     Because the control inherits from CreateMerchandiseModuleBase you have access to any custom properties
    ///     defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
    /// </summary>
    /// -----------------------------------------------------------------------------
    public  partial class View : CreateMerchandiseModuleBase, IActionable
    {
        public static readonly String StrPortalId =
            PortalController.Instance.GetCurrentPortalSettings().PortalId.ToString();
        public String curVariantId="";
        public GridView gvStore;
        public ModuleActionCollection ModuleActions
        {
            get
            {
                var actions = new ModuleActionCollection
                {
                    {
                        GetNextActionID(), Localization.GetString("EditModule", LocalResourceFile), "", "", "",
                        EditUrl(), false, SecurityAccessLevel.Edit, true, false
                    }
                };
                return actions;
            }
        }


        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                gvVariants.DataSource = GetVariantTable(StrPortalId);
                gvVariants.DataBind();
                //Session["gvStore"] = gvVariants;
                Session["gvStore"] = gvVariants.DataSource;
            }
            else
            {
                //gvVariants = (GridView)Session["gvStore"];
                //gvVariants.DataSource = (DataTable)((GridView)Session["gvStore"]).DataSource;
                gvVariants.DataSource = (DataTable)Session["gvStore"];
                gvVariants.DataBind();
            }
        }


        protected void gvVariants_OnRowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {         
                //curVariantId= gvVariants.DataKeys[e.Row.RowIndex].Value.ToString();
                curVariantId = ((DataRowView) e.Row.DataItem)[0].ToString();
                GridView gvValues = e.Row.FindControl("gvValues") as GridView;
                using (var ipv = new IMM_ProductVariantValuesController())
                {
                    ipv.Gets(curVariantId,"IMM_ProductVariants_ID",pWhere: $"and (portal_id=-1 or portal_id={PortalId})");
                    if (!ipv.Recordset.Any())
                    {
                        ipv.Recordset.Add(new IMM_ProductVariantValues()
                        {
                            ID=-1
                        });
                    }
                    ipv.LoadDatatable();
                    gvValues.DataSource = ipv.Datatable;
                    gvValues.DataBind();
                }
            }      
        }

        protected void gvValues_OnRowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)

            {
                if (((DataRowView)e.Row.DataItem)[0].ToString() == "-1")
                {
                    e.Row.Visible = false;
                }
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                Button b = e.Row.FindControl("btnAddValue") as Button;
                b.OnClientClick = "SetID('" +curVariantId+"')";
            }
        }

        protected void btnAddValue_Click(object sender, EventArgs e)
        {
            GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);

            string myID = hfVariantID.Value;
            TextBox txtNewValue = (TextBox)row.FindControl("NewValue");
            using (var ipvv = new IMM_ProductVariantValuesController())
            {
                ipvv.Recordset.Add(new IMM_ProductVariantValues()
                {
                    IMM_ProductVariants_ID = Convert.ToInt32(myID),
                    Portal_ID = Convert.ToInt32(StrPortalId),
                    VariantValue = txtNewValue.Text.Trim().TrimStart(',') //remove leading PostBack comma
            });
                ipvv.Inserts();
            }
        }

        protected void btnAddVariant_Click(object sender, EventArgs e)
        {
            GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
            TextBox txtNewValue = (TextBox)row.FindControl("NewVariant");
            using (var ipv = new IMM_ProductVariantsController())
            {
                ipv.Recordset.Add(new IMM_ProductVariants()
                {
                    Portal_ID = Convert.ToInt32(StrPortalId),
                    Name = txtNewValue.Text.Trim().TrimStart(',') //remove leading PostBack comma
                });
                ipv.Inserts();
            }
        }

        protected void gvVariants_OnRowCommand(Object sender, GridViewCommandEventArgs e)
        {
            gvVariants.DataSource = GetVariantTable(StrPortalId);
            gvVariants.DataBind();
            Session["gvStore"] = gvVariants.DataSource;
        }

    }
}