【问题标题】:c#.net gridview with both (sometimes displayed) button click and row click eventsc#.net gridview 与(有时显示)按钮单击和行单击事件
【发布时间】:2018-01-18 01:52:20
【问题描述】:

我有一个具有以下定义的网格。我在这里包含了两个按钮(不同类型),但我真的只想要一个,但它必须能够在某些情况下隐藏。
使用“ButtonField”,我可以将其隐藏在 RowDataBound 事件中,但是,在回发(行单击事件)时,所有按钮都会显示。
单击此按钮会触发两个 RowCommand 事件,一个是“Select”,一个是“AcceptStats”,如果我可以在不需要时隐藏该按钮就可以了。

'asp:Button'一直正确显示,但是点击事件似乎在行点击事件下丢失了。
在 RowCommand 事件中,CommandName 始终为“Select”,它来自行单击事件。 我尝试将 OnClick="btnAcceptStats_Click" 添加到 asp:Button,但它也不会触发。

<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";


        }
    }

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

【问题讨论】:

  • 请具体说明
  • 嗨 Asif.Ali,我不确定您所说的“请具体说明”是什么意思?

标签: c# asp.net button gridview


【解决方案1】:

如果您想隐藏按钮,为什么不将它们的可见性基于 GridView 内联的值。

<asp:Button ID="Button2" runat="server" Visible='<%# Convert.ToBoolean(Eval("myBool")) %>' Text="Button 1" />

<asp:Button ID="Button1" runat="server" Visible='<%# !Convert.ToBoolean(Eval("myBool")) %>' Text="Button 2" />

【讨论】:

    【解决方案2】:

    感谢您的回复。我的 asp:Button 使用以下代码正确显示:

    visible='<%# Eval("IsMerged").ToString().ToLowerInvariant().Equals("false") %>'
    

    问题是,当我使用这个按钮时,我无法让按钮点击事件工作,只有行点击事件。当我单步执行 RowCommand 时,CommandName 只是“选择”。我无法触发“AcceptStats”事件。

    【讨论】:

      【解决方案3】:

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

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

      <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));
                      }
                  }
      
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-11
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多