在网格视图中更改单元格值时发出警报

时间:2014-03-04 12:29:45

标签: c# asp.net .net gridview

我有一个带有下拉值的gridview和一个页面中的更新按钮。每当用户更改下拉列表中的任何值并尝试离开页面(分页)时,都会弹出确认警报。如果他们单击“确定”,则必须导航到所选索引页面,如果单击“取消”,则必须保持在同一页面上。无论如何,我可以跟踪更改的单元格值,并在用户尝试进行分页或移动到其他页面而不单击页面中的更新按钮时发出警报。

有关如何实现这一目标的任何建议。

2 个答案:

答案 0 :(得分:1)

您可以使用此链接here在gridview中添加下拉列表,在下拉列表的更改事件中,您可以向viewstate变量添加boolean值,例如

  

ViewState [“IsDDChanged”] = true;

然后您可以注册gridview的PageIndexChanging事件并检查viewstate中的值是否为true,然后您可以使用“RegisterStartupScript”或“RegisterClientScriptBlock”注册javascript。关于如何注册javascript的链接是here

注册javascript后,您可以在同一事件中或通过上述注册javascript中的ajax调用将viewstate设置为false,具体取决于您的要求。这对于下次工作很重要。您甚至可以取消分页事件。该链接here

中提供了该事件和一个很好的示例

这些可能会给你一个好的方向。

希望这有帮助。

修改

我有一些时间,所以为你做了这个小POC。 将aspx和aspx.cs代码复制到一个单独的项目中,并检查这是否是您需要的

以下是我遵循的步骤

  1. 创建了RowCreated事件并使用它添加了下拉列表
  2. 使用PageIndexChanging事件和使用ScriptManager.RegisterStartupScript
  3. 注册的javascript
  4. 添加了一个按钮并将其隐藏
  5. 如果下拉列表已更改且页面已更改,则会弹出确认。如果确认是肯定的,则从javascript点击按钮事件,如果没有下拉列表发生更改,则依次为gridview做分页,然后继续正常分页
  6. 我已经完成了几点,你需要记住

    1. @Page指令中,我已经EnableEventValidation="false"。这是必需的,以便我可以触发隐藏按钮的click事件,但这不是一个好习惯,因为它会降低安全性。要获得更安全的方式,您应该使用UpdatePanel AJAX extensions。{/ li>
    2. 我使用了隐藏按钮的点击事件而不是JQuery AJAX,因为它需要代码隐藏中的静态方法,我们将无法在静态方法中设置gridview的分页。否则你需要从AJAX调用发送gridview的对象,但这对我来说太麻烦了。
    3. 对于下拉列表,
    4. AutoPostBacktrue非常重要,否则您的selectedIndexChanged事件不会被解雇。即ddlDesignation.AutoPostBack = true;
    5. <强> ASPX

      <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Grid_Practice.aspx.cs"
          EnableEventValidation="false" Inherits="Practice_Web.Grid_Practice" %>
      
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head id="Head1" runat="server">
          <title></title>
          <script type="text/javascript" language="javascript">
              function ConfirmUser(msg) {
                  if (confirm(msg)) {
                      __doPostBack('Button1', 'OnClick');
                  }
              }
          </script>
      </head>
      <body>
          <form id="form1" runat="server">
          <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
          </asp:ScriptManager>
          <div>
              <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" Style="display: none;" />
              <asp:GridView ID="GridView1" runat="server" OnPageIndexChanging="GridView1_PageIndexChanging"
                  AllowPaging="true" PageSize="10" AutoGenerateColumns="false" OnRowCreated="GridView1_RowCreated">
                  <PagerSettings Mode="NextPreviousFirstLast" FirstPageText="First" LastPageText="Last"
                      NextPageText="Next" PreviousPageText="Prev" Position="TopAndBottom" />
                  <Columns>
                      <asp:BoundField />
                  </Columns>
              </asp:GridView>
          </div>
          </form>
      </body>
      </html>
      

      <强> aspx.cs

      namespace Practice_Web
      {
          public partial class Grid_Practice : System.Web.UI.Page
          {
              protected void Page_Load(object sender, EventArgs e)
              {
                  if (!IsPostBack)
                  {
                      //Dummy value for gridview
                      DataTable dt1 = new DataTable();
                      dt1.Columns.Add(new DataColumn("Designation", typeof(String)));
      
                      DataRow dr = null;
                      for (int i = 0; i < 15; i++)
                      {
                          dr = dt1.NewRow();
      
                          dr[0] = "designation" + (i % 2);
                          dt1.Rows.Add(dr);
                      }
      
                      Session["dt"] = dt1;
                      GridView1.DataSource = dt1;
                      GridView1.DataBind();    
                  }
      
              }
      
              protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
              {
                  Session["NewPageIndex"] = e.NewPageIndex;
                  var sessionVar = Session["dropdownChanged"];
                  bool dropdownChanged = false;
      
                  if (sessionVar != null)
                      dropdownChanged = Convert.ToBoolean(Session["dropdownChanged"]);
      
                  if (dropdownChanged)
                  {
                      ScriptManager.RegisterStartupScript(this, typeof(string), "Error", "ConfirmUser('Are u sure');", true);
                  }
                  else
                  {
                      ChangeGridPage();
                  }
              }
      
              public void ChangeGridPage()
              {
                  int pageIndex = Convert.ToInt32(Session["NewPageIndex"]);
                  GridView1.PageIndex = pageIndex;
                  GridView1.DataSource = (Session["dt"] as DataTable);
                  GridView1.DataBind();
              }
      
              protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
              {
                  if (e.Row.RowType == DataControlRowType.DataRow)
                  {
                      DropDownList ddlDesignation = new DropDownList();
                      ddlDesignation.SelectedIndexChanged += new EventHandler(ddlDesignation_SelectedIndexChanged);
                      ddlDesignation.AutoPostBack = true;
      
                      ddlDesignation.ID = "MyID" + e.Row.RowIndex.ToString();
      
                      DataTable dt1 = new DataTable();
                      dt1.Columns.Add(new DataColumn("Designation", typeof(String)));
      
                      DataRow dr = null;
                      dr = dt1.NewRow();
                      dr[0] = "designation0";
                      dt1.Rows.Add(dr);
      
                      dr = dt1.NewRow();
                      dr[0] = "designation1";
                      dt1.Rows.Add(dr);
      
                      ddlDesignation.DataSource = dt1;
                      ddlDesignation.DataTextField = "Designation";
                      ddlDesignation.DataValueField = "Designation";
                      ddlDesignation.DataBind();
                      ddlDesignation.Items.Insert(0, new ListItem("--Select--", "0"));
      
                      ddlDesignation.SelectedValue = (Session["dt"] as DataTable).Rows[e.Row.RowIndex][0].ToString();
      
                      e.Row.Cells[0].Controls.Add(ddlDesignation);
                  }
              }
      
              void ddlDesignation_SelectedIndexChanged(object sender, EventArgs e)
              {
                  Session["dropdownChanged"] = true;
                  //other code here
              }
      
              protected void Button1_Click(object sender, EventArgs e)
              {
                  ChangeGridPage();
              }
          }
      }
      

      希望这可以解决您的问题

答案 1 :(得分:0)

这似乎是一个很长的答案,但它非常容易应用。

作为此场景的临时(替代但正常工作)解决方案,我在MSDN中找到了关于创建为GridView创建自己的PagerTemplate的文章。寻呼机将在DropDownList中,它非常有趣并且可以更灵活地实现您的需求,我在代码中进行了一些修改以达到要求。

在Markup中,将GridView修改为:

<asp:GridView ID="gridUsers" runat="server"  ShowHeaderWhenEmpty="true" AutoGenerateColumns="False" 
    OnDataBound="CustomersGridView_DataBound"
HorizontalAlign="Center" Width="100%" AllowPaging="True" >
 <pagerstyle forecolor="Blue"
  backcolor="LightBlue"/>

<PagerTemplate>
  <table width="100%">                    
    <tr>                        
      <td style="width:70%">

        <asp:label id="MessageLabel"
          forecolor="Blue"
          text="Select a page:" 
          runat="server"/>
        <asp:dropdownlist id="PageDropDownList"
          onselectedindexchanged="PageDropDownList_SelectedIndexChanged"  
        AutoPostBack="true"              
        onChange="if(!confirm('Continue without saving?! Data will be lost!'))return false;"
         runat="server"/>
      </td>   

      <td style="width:70%; text-align:right">

        <asp:label id="CurrentPageLabel"
          forecolor="Blue"
          runat="server"/>
      </td>

    </tr>                    
  </table>

</PagerTemplate> 
    <Columns>   
    <!-- columns -->
    </Columns>

</asp:GridView> 

接下来,添加以下函数(我正在使用VB.Net):

Protected Sub PageDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)

    ' Retrieve the pager row.
    Dim pagerRow As GridViewRow = gridUsers.BottomPagerRow

    'Retrieve the PageDropDownList DropDownList from the bottom pager row.
    Dim pageList As DropDownList = DirectCast(pagerRow.Cells(0).FindControl("PageDropDownList"), DropDownList)

    ' Set the PageIndex property to display that page selected by the user.
    gridUsers.PageIndex = pageList.SelectedIndex
    SelectData()
End Sub

最后,添加以下功能:

 Protected Sub CustomersGridView_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Retrieve the pager row.
        Dim pagerRow As GridViewRow = gridUsers.BottomPagerRow

        'Retrieve the PageDropDownList DropDownList from the bottom pager row.
        Dim pageList As DropDownList = DirectCast(pagerRow.Cells(0).FindControl("PageDropDownList"), DropDownList)

        Dim pageLabel As Label = DirectCast(pagerRow.Cells(0).FindControl("CurrentPageLabel"), Label)

        If pageList IsNot Nothing Then

            For i As Integer = 0 To gridUsers.PageCount

                Dim pageNumber As Integer = i + 1
                Dim item As New ListItem(pageNumber.ToString())


                If i = gridUsers.PageIndex Then

                    item.Selected = True
                End If

                pageList.Items.Add(item)
            Next

        End If

        If pageLabel IsNot Nothing Then  
            Dim currentPage As Integer = gridUsers.PageIndex + 1
            pageLabel.Text = "Page " + currentPage.ToString() + " of " + gridUsers.PageCount.ToString()

        End If
    End Sub

我确信这不是最好的解决方案,但它很有趣。请注意,我已经修改了DropDownList设计并添加了“OnChange”事件,该事件将执行客户端警报技巧。

但是,如果用户取消了回发,还有一件事需要弄清楚哪些是返回DropDownList中的旧页码,我想你只是创建一个javascript函数来实现它。< / p>

希望这有帮助。