c#.net gridview同时(有时显示)按钮单击和行单击事件 [英] c#.net gridview with both (sometimes displayed) button click and row click events

查看:53
本文介绍了c#.net gridview同时(有时显示)按钮单击和行单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下定义的网格.我在这里包括了两个按钮(不同类型),但是我确实只想要一个按钮,但是在某些情况下必须能够将其隐藏.
使用"ButtonField",我可以将其隐藏在RowDataBound事件中,但是,在回发(行单击事件)时,所有按钮都在显示的地方.
单击此按钮将触发两个RowCommand事件,一个是选择"事件,另一个是"AcceptStats"事件,如果我可以在不希望的时候隐藏该按钮,那就可以了.

I have a grid with the following definition. I have included two buttons here (different types), but I really only want one, but it must be able to be hidden under certain circumstances.
With the 'ButtonField' I was able to hide it in the RowDataBound event, however, on postback (row click event), all buttons where displayed.
Clicking this button triggers two RowCommand events, one being 'Select' and one being the 'AcceptStats', which would be okay if I could hide the button when not wanted.

"asp:Button"始终正确显示,但单击事件似乎在行单击事件下丢失了.
在RowCommand事件中,CommandName始终为选择",它来自行单击事件.我尝试将OnClick ="btnAcceptStats_Click"添加到asp:Button,但它不会触发任何一个.

The 'asp:Button' displays correctly all the time, but the click event seems to have gotten lost under the row click event.
In the RowCommand event, the CommandName is always 'Select', which comes from the row click event. I have tried adding OnClick="btnAcceptStats_Click" to the asp:Button, but it doesn't trigger either.

<asp:GridView ID="gvApsimFiles" runat="server" AutoGenerateColumns="false" CssClass="GridViewStyle" 
    PageSize="10" AllowPaging="true" DataKeyNames="PullRequestId, RunDate"
    OnPageIndexChanging="gvApsimFiles_PageIndexChanging" 
    OnRowCommand="gvApsimFiles_RowCommand"
    OnRowDataBound="gvApsimFiles_RowDataBound"
    OnSelectedIndexChanged="gvApsimFiles_SelectedIndexChanged" >
    <HeaderStyle CssClass="GridViewHeaderStyle" />
    <Columns>
        <asp:BoundField DataField="PullRequestId" HeaderText="Pull Request Id" ItemStyle-Width="100px" />
        <asp:BoundField DataField="RunDate" HtmlEncode="false" HeaderText="Run Date" ItemStyle-Width="220px" DataFormatString="{0:d MMMM, yyyy hh:mm tt}" />
        <asp:BoundField DataField="IsMerged" HeaderText="Is Merged" ItemStyle-Width="100px" />
        <asp:BoundField DataField="PercentPassed"  HtmlEncode="false" HeaderText="Percent<br />Passed" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="100px" />
        <asp:BoundField DataField="Total" HeaderText="Total Files" ItemStyle-HorizontalAlign="Right"  ItemStyle-Width="100px" />
        <asp:ButtonField ButtonType="Button" ItemStyle-Font-Size="11px" Text="Accept Stats" CommandName="AcceptStats" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="btnAcceptStats" runat="server" Text="Accept Stats"
                    CommandName="AcceptStats"
                    CommandArgument='<%# Container.DataItemIndex %>' 
                    OnClick="btnAcceptStats_Click"
                />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

在后面的代码中:

    protected void btnAcceptStats_Click(object sender, EventArgs e)
    {
        GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
        int index = gvRow.RowIndex;

        int pullRequestId = int.Parse(gvApsimFiles.Rows[index].Cells[0].Text);
        //Now we can call our web api 'merge' call
        bool mergeStatus = bool.Parse(gvApsimFiles.Rows[index].Cells[2].Text);
        if (!mergeStatus)
        {
            UpdatePullRequestMergeStatus(pullRequestId, true);
        }

    }

    protected void gvApsimFiles_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvApsimFiles.PageIndex = e.NewPageIndex;
        BindApsimFilesGrid();
    }

    protected void gvApsimFiles_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "AcceptStats")
        {
            var eVal = Convert.ToInt32(e.CommandArgument);
            int index = int.Parse(eVal.ToString());
            int pullRequestId = int.Parse(gvApsimFiles.Rows[index].Cells[0].Text);
            //Now we can call our web api 'merge' call
            bool mergeStatus = bool.Parse(gvApsimFiles.Rows[index].Cells[2].Text);
            if (!mergeStatus)
            {
                UpdatePullRequestMergeStatus(pullRequestId, true);
            }
        }
    }

    protected void gvApsimFiles_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //Show as green if 100% 
            if (e.Row.Cells[3].Text.Equals("100"))
            {
                e.Row.ForeColor = Color.Green;
            }
            //Activate the row click event
            e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvApsimFiles, "Select$" + e.Row.RowIndex);
            e.Row.Attributes["style"] = "cursor:pointer";


        }
    }

有没有一种方法可以让我在保持行单击事件的同时仅在需要时显示,不会在回发时重新出现并正确触发?

Is there a way that I can have a button, that is only displayed when required, doesn't re-appear on postback, and triggers correctly, while maintaining the row click event?

推荐答案

我找到了一个解决方案.通过使用Gridview_RowDataBound,更新网格中的每个单元格,然后在Gridview_RowCommand上,检索这些值,然后从那里开始.

I have found a solution. It is through the use of Gridview_RowDataBound, updating each cell in the grid, and then on the Gridview_RowCommand, retrieving these values, and going from there.

加载速度稍慢,但可以..aspx页上的工作代码如下:

It is slightly slower to load, but works. The working code on the .aspx page is as follows:

<asp:GridView ID="gvApsimFiles" runat="server" AutoGenerateColumns="false" CssClass="GridViewStyle" 
    PageSize="10" AllowPaging="true" DataKeyNames="PullRequestId, RunDate"
    OnPageIndexChanging="gvApsimFiles_PageIndexChanging" 
    OnRowCommand="gvApsimFiles_RowCommand"
    OnRowDataBound="gvApsimFiles_RowDataBound" >
    <HeaderStyle CssClass="GridViewHeaderStyle" />
    <RowStyle CssClass="GridViewRowStyle" />
    <Columns>
        <asp:BoundField DataField="PullRequestId" HeaderText="Pull Request Id" ItemStyle-Width="100px" />
        <asp:BoundField DataField="RunDate" HtmlEncode="false" HeaderText="Run Date" ItemStyle-Width="220px" DataFormatString="{0:d MMMM, yyyy hh:mm tt}" />
        <asp:BoundField DataField="IsMerged" HeaderText="Is Merged" ItemStyle-Width="100px" />
        <asp:BoundField DataField="PercentPassed"  HtmlEncode="false" HeaderText="Percent<br />Passed" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="100px" />
        <asp:BoundField DataField="Total" HeaderText="Total Files" ItemStyle-HorizontalAlign="Right"  ItemStyle-Width="100px" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="btnAcceptStats" runat="server" Text="Accept Stats"
                    Visible='<%# Eval("IsMerged").ToString().ToLowerInvariant().Equals("false") %>'
                />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

后面的代码是:

   protected void gvApsimFiles_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // Don't interfere with other commands.
        // We may not have any now, but this is another safe-code strategy.
        if (e.CommandName == "CellSelect")
        {
            // Unpack the arguments.
            String[] arguments = ((String)e.CommandArgument).Split(new char[] { ',' });

            // More safe coding: Don't assume there are at least 2 arguments.
            // (And ignore when there are more.)
            if (arguments.Length >= 2)
            {
                // And even more safe coding: Don't assume the arguments are proper int values.
                int rowIndex = -1, cellIndex = -1;
                bool canUpdate = false;
                int.TryParse(arguments[0], out rowIndex);
                int.TryParse(arguments[1], out cellIndex);
                bool.TryParse(arguments[2], out canUpdate);

                // Use the rowIndex to select the Row, like Select would do.
                if (rowIndex > -1 && rowIndex < gvApsimFiles.Rows.Count)
                {
                    gvApsimFiles.SelectedIndex = rowIndex;
                }

                //here we either update the Update Panel (if the user clicks only anything OTHER THAN our'Button'
                //or we process the UpdatePullRequest as Merged
                if (cellIndex == 5 && canUpdate == true)
                {
                    int pullRequestId = int.Parse(gvApsimFiles.Rows[rowIndex].Cells[0].Text);
                    UpdatePullRequestMergeStatus(pullRequestId, true);
                }
                else
                {
                    int pullRequestId = int.Parse(gvApsimFiles.Rows[rowIndex].Cells[0].Text);
                    BindSimFilesGrid(pullRequestId);

                }
            }
        }

    }

    protected void gvApsimFiles_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //Show as green if 100% 
            if (e.Row.Cells[3].Text.Equals("100"))
            {
                e.Row.ForeColor = Color.Green;
            }
            e.Row.Attributes["style"] = "cursor:pointer";

            //Active cell click events on individual cells, instead of the row
            foreach (TableCell cell in e.Row.Cells)
            {
                // Although we already know this should be the case, make safe code. Makes copying for reuse a lot easier.
                if (cell is DataControlFieldCell)
                {
                    int cellIndex = e.Row.Cells.GetCellIndex(cell);
                    bool canUpdate = false;
                    // if we are binding the 'Button' column, and the "IsMerged' is false, then whe can Update the Merge Status.
                    if (cellIndex == 5 && e.Row.Cells[2].Text.ToLower().Equals("false"))
                    {
                        canUpdate = true;
                    }
                    // Put the link on the cell.
                    cell.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvApsimFiles, String.Format("CellSelect${0},{1},{2}", e.Row.RowIndex, cellIndex, canUpdate));

                    // Register for event validation: This will keep ASP from giving nasty errors from getting events from controls that shouldn't be sending any.
                    Page.ClientScript.RegisterForEventValidation(gvApsimFiles.UniqueID, String.Format("CellSelect${0},{1},{2}", e.Row.RowIndex, cellIndex, canUpdate));
                }
            }

        }
    }

这篇关于c#.net gridview同时(有时显示)按钮单击和行单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆