0

我的 gridview 页脚中有一个带有 autopostack=true 的复选框(它应该触发一个 checkchanged 事件),我的 itemtemplate 中有一个链接按钮(它应该触发 gridview rowcommand 事件)。

一切正常,直到我将以下代码放入我的 gridview 行数据绑定(或数据绑定)事件中:

        for (int i = 0; i < gridCartRows.Columns.Count - 2; i++)
        {
            e.Row.Cells.RemoveAt(0);
        }

        e.Row.Cells[0].ColumnSpan = gridCartRows.Columns.Count - 1; 

现在,当我单击我的链接按钮时,复选框 checkedchanged 事件被自动触发,然后 rowcommand 事件被触发。

当我添加上面的代码时,为什么不应该触发 checkchanged 事件?

有没有办法解决这个问题?

编辑

这是一个示例,它重现了我的问题:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="True"
        OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="Column1">
                <ItemTemplate>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Column2">
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" Text="Fire Row Command" CommandName="Fire" />
                </ItemTemplate>
                <FooterTemplate>
                    Footer
                    <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox1_CheckedChanged" />
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Column3">
                <ItemTemplate>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = new int[5];
        GridView1.DataBind();
    }
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        for (int i = 0; i < GridView1.Columns.Count - 2; i++)
        {
            e.Row.Cells.RemoveAt(0);
        }
        e.Row.Cells[0].ColumnSpan = GridView1.Columns.Count - 1;

        ((CheckBox)e.Row.FindControl("CheckBox1")).Checked = true;
    }
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Fire")
    {
        Response.Write("RowCommand fired.");
    }
}

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
    Response.Write("CheckBox fired.");
}

请注意,我在 RowDataBound 中将 CheckBox 属性设置为 true - 如果我删除它,它可以正常工作。所以合并单元格和设置复选框属性不能很好地协同工作。

4

1 回答 1

2

GridView 控件事件存储在视图状态中,它们很容易搞砸。此处删除导致将不同事件绑定到链接按钮的单元格。虽然回发后 __EVENTTARGET 是 LinkBut​​ton,但调用了错误的方法和错误的控件,传递了事件参数。

我建议隐藏单元格而不是删除它:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[1].ColumnSpan = GridView1.Columns.Count - 1;
        e.Row.Cells[0].Visible = false;

        ((CheckBox)e.Row.FindControl("CheckBox1")).Checked = true;
    }
}

这将达到目的。

于 2013-10-17T20:53:05.477 回答