【问题标题】:Refresh C# GridView data on postback在回发时刷新 C# GridView 数据
【发布时间】:2015-04-14 22:38:17
【问题描述】:

所以,这就是我的场景

我有这个gridview,在一个自定义控件中。该网格的每个行元素都可以在单独的弹出窗口中打开以编辑其详细信息(是的,弹出窗口,这是客户想要的方式)

因此,为了编辑和检索这一行编辑数据,我将其存储在 Session 变量中,以便在弹出窗口和稍后显示详细信息

    ObjectType editObject = CurrentDS.FirstOrDeafult(o => o.Index == e.CommandArgument);
     Session["EditObjectVar"] = editObject;
     ScriptManager.RegisterStartupScript(this.Page, typeof(string), "OPEN_WINDOW", "window.open('ObjDetails.aspx', '_blank','scrollbars=yes,status=yes,toolbar=no,menubar=no,location=no,resizable=1,width=700,height=425,center=yes' );", true);

关闭并保存更改时,我再次存储在同一个 Session 变量上,并在父窗口上强制回发以刷新数据。

   Session.Remove("EditObjectVar");
    StoreValuesOnObject();
    Session["EditObjectVar"] = editObject;
    ScriptManager.RegisterStartupScript(this.Page, GetType(), "Close Popup", "window.opener.__doPostBack();window.close();", true);

在控件 page_load 事件上,我检查是否有回发并且 Session 变量有数据,我需要刷新 DS 和 gridview 上的对象。

if (Page.IsPostBack && Session["EditObjectVar"] != null)
{
    ObjectType modObj = (ContainerType) Session["EditObjectVar"];
    ObjectType oldObj = CurrentDS.FirstOrDeafult(o => o.Index == modObj .Index);
    CurrentDS.Remove(oldObj);
    CurrentDS.Add(modObj);
    gv.DataSource = null;
    gv.DataSource = CurrentDS;
    gv.DataBind();
    Session.Remove("EditObjectVar");
}

一切都正确保存,我检索编辑的对象,更重要的是,考虑到在 Session 变量上,除了存储对象之外,还存储了对象内存位置,这意味着,通过强制回发,编辑的对象已经在网格数据源上更新(也存储在 Session 变量中),所以我将 gridview 绑定到更新的 DS,使用更新的对象,但是仍然没有刷新 gridview,它仍然从 viewstate 中检索行状态

知道如何完成我的任务吗?更新面板是一个选项,我知道,但我没有使用它们的绿灯

我已经有类似的东西,对象详细信息,还包含在详细信息弹出窗口中显示在网格视图上的对象集合,作为其父对象,用户还可以在单​​独的弹出窗口中打开子对象的详细信息窗户。之前描述的逻辑在这里适用,但是使用对象详细信息,对象子对象gridview正确刷新!

已编辑:添加尽可能多的代码以便更好地解释,因为我签订了非常严格的保密协议,并且在线发布真实代码可能会带来一些麻烦,但我已经没有想法

编辑2:忘记在示例中添加.DataBind(),但它在代码中

编辑 3:忘了提一下,它不刷新的 GridView 具有能够直接在 gridview 上更改某些值的控件。这是gridview的html

    <asp:GridView ID="gv" runat="server" ShowHeader="false" CellPadding="5" CellSpacing="0" EnableViewState="true" AutoGenerateColumns="False" OnRowCreated="RowCreated" 
    OnRowDataBound="RowDataBound"  GridLines="Both" BorderStyle="Solid" BorderColor="Black" BorderWidth="1px">
    <Columns>

     <asp:TemplateField>
            <ItemTemplate>
               <asp:ImageButton ID="imgDelete" runat="server"   CausesValidation="false"  AlternateText="Delete Part"
                     CommandName="cnt_delete" CommandArgument='<%# Eval("ContainerIndex") %>'  OnClick="imgDelete_Click"
                    ImageUrl="~/img/del.png" />
               <asp:ImageButton ID="imgDetails" runat="server"   CausesValidation="false"  AlternateText="View Cnt Details"
                     CommandName="cnt_details" CommandArgument='<%# Eval("ContainerIndex") %>'
                    ImageUrl="~/img/edit_icon.png" Height="15px" onclick="imgDetails_Click" />
                <asp:Label ID="lblNum" runat="server"  Text='<%# Eval("ContainerIndex") %>' ></asp:Label>
            </ItemTemplate>
            <ItemStyle  CssClass="subGridItem" VerticalAlign="Top" />
        </asp:TemplateField>        
     <asp:TemplateField>
            <ItemTemplate>
                <table style="FONT-SIZE: xx-small; FONT-FAMILY: Verdana; background-color:#F5F5F5" cellspacing="1" cellpadding="1"
            border="0" width="100%" >           
            <tr>                                            

                <td>
                      <asp:Label ID="lblQty" runat="server" Text="Qty" ></asp:Label>
                      <asp:Label ID="lblQtyRq" runat="server"  Text="*"></asp:Label>
                </td>
                    <td style="white-space:nowrap">
                     <asp:Label ID="lblWeight" runat="server" Text="Weight" ></asp:Label>
                     <asp:Label ID="lblWeightRq" runat="server"  Text="*"></asp:Label>
                </td>       
                <td style="white-space:nowrap">
                     <asp:Label ID="lblCntType" runat="server" Text="Container Type" ></asp:Label>
                     <asp:Label ID="lblCntTypeRq" runat="server"  Text="*"></asp:Label> 
                </td>

            </tr>
            <tr valign="top">           

            <td><asp:TextBox ID="txtQty"  Width="50px" runat="server" CssClass="detailsInput" Text='<%# Eval("Quantity") %>' MaxLength="7" ></asp:TextBox><br />
                <asp:RequiredFieldValidator ID="validatorQty" runat="server" ControlToValidate="txtQty" Display="Dynamic" ErrorMessage="Required" ></asp:RequiredFieldValidator>
                <asp:CompareValidator ID="CompareQty" runat="server"  Display="Dynamic" ControlToValidate="txtQty" Operator="GreaterThan" ValueToCompare="0" Type="Double"  ErrorMessage="invalid"></asp:CompareValidator>  
           </td>
                <td><asp:TextBox ID="txtWeight" Width="50px" runat="server" CssClass="detailsInput" Text='<%# Eval("Weight") %>' MaxLength="11" ></asp:TextBox><br />
                <asp:RequiredFieldValidator ID="ValidatorWgt" runat="server" ControlToValidate="txtWeight" Display="Dynamic" ErrorMessage="Required"></asp:RequiredFieldValidator>
                <asp:CompareValidator ID="CompareWeight" runat="server" Display="Dynamic" ControlToValidate="txtWeight" Operator="GreaterThan" ValueToCompare="0" Type="Double"  ErrorMessage="invalid"></asp:CompareValidator>
            </td>
            <td>
                <asp:DropDownList ID="lstCntTypes" runat="server"  ></asp:DropDownList><br />
                <asp:RequiredFieldValidator ID="validatorCntTypes" runat="server" CssClass="TPValidator" ControlToValidate="lstCntTypes" Display="Dynamic" ErrorMessage="Required"></asp:RequiredFieldValidator>
            </td>
            </tr>
            <tr><td colspan="12">
            <table width="100%" >
            <tr>                
                <td style="white-space:nowrap">
                    <asp:label id="lblProperShippingName" CssClass="TPLabel"  Runat="server" Visible="false">Proper shipping name</asp:label>
                    <asp:label id="lblProperShippingNameM" Runat="server" ForeColor="red" Font-Size="xx-small" Visible="false">*</asp:label></td>
                <td style="white-space:nowrap">
                    <asp:label id="lblHazClass" CssClass="TPLabel"  Runat="server" Font-Size="xx-small" Visible="false">Hazard class</asp:label>
                    <asp:label id="lblHazClassM" Font-Bold="true" Runat="server" ForeColor="red" Font-Size="xx-small" Visible="false">*</asp:label>
                </td>               
                <td style="white-space:nowrap">
                    <asp:label id="lblUNNumber" CssClass="TPLabel"  Runat="server" Visible="false" >UN/NA Identification Number</asp:label>
                    <asp:label id="lblUNNumberM" Runat="server" ForeColor="red" Font-Size="xx-small" Visible="false">*</asp:label>
                </td>
                <td style="white-space:nowrap">
                    <asp:label id="lblPackGroup" CssClass="TPLabel"  Runat="server" Visible="false" >Packing group</asp:label>
                    <asp:label id="lblPackGroupM" Font-Bold="true" Runat="server" ForeColor="red" Visible="false" >*</asp:label>
                </td>
                <td>
                    <asp:label id="lblIMO" CssClass="TPLabel"  Runat="server" Visible="False">IMO Classification</asp:label></td>
                <td><asp:label id="lblTunnel" CssClass="TPLabel" Runat="server" Visible="False">Tunnel Restriction</asp:label></td>
            </tr>
            </table>
           </td>        </tr>
        <tr>
        <td colspan="8">   </td></tr>
        </table>
            </ItemTemplate>
      <ItemStyle VerticalAlign="Top" />     
        </asp:TemplateField>  
    </Columns>
</asp:GridView>

您可以在此处注意到,两个 txt 输入都从行属性的 eval 中获取它们的值,但 lst 没有。第一个值是在 RowDataBound 事件上设置的,我可以在那里看到修改后的值,但它仍然显示取自 viewstate 的值

【问题讨论】:

  • 我希望没有人允许您使用 UpdatePanels。他们的麻烦比他们的价值要多得多。无论如何,您应该发布您的代码并显示您尝试使用新信息更新 GV 的位置。创建一个Minimal, Complete, and Verifiable example
  • @mason 那么,如果我想在需要使用库存控件的项目中使用类似 AJAX 的功能,我可以使用什么。我以前使用过 DevExpress 控件,并且使用它们的控件进行回调非常容易,但是像这个只想要库存控制的客户,我怎么能去呢?其他几个页面已经使用更新面板
  • AJAX!不认真,您最好直接使用 AJAX(也许借助诸如 jQuery AJAX 之类的帮助程序库)比使用 UpdatePanel 的低效抽象要好得多。在服务器端,ASP.NET Web API 或 WCF 用于响应 AJAX 调用(不要使用网页/页面方法!)。对于股票,SignalR 在某些情况下也可能适用。另见How to implement real time data for a web page
  • mason 谢谢,我确定你可能会提到像 JQUERY 一样的股票 AJAX,我也更喜欢编写纯 html5/jquery/js/css 页面而不是 asp.net Web 表单并添加服务器端的一些rest/wcf。见鬼,现在每次我被告知要创建 Web 表单而不是 MVC 时,我都会感到畏缩!

标签: c# asp.net gridview


【解决方案1】:

所以,我终于解决了这个问题并让它发挥作用。

最后,我在网格所在的同一个自定义控件上设置了一个按钮,并让该控件检索它在 Session 上的信息并刷新网格,而不是在回调时这样做

编辑:这个按钮被 css 隐藏在用户的视线之外(显示:无)。不是很花哨的方法,但是,它有效

因此,在检索要编辑的对象时,我还将刷新 DS 的按钮的 UniqueID 存储在 Session 中

 ObjectType editObject = CurrentDS.FirstOrDeafult(o => o.Index == e.CommandArgument);
     Session["EditObjectVar"] = editObject;
     Session["BtnRefreshUniqueID"] = btnRefreshDS.UniqueID;
     ScriptManager.RegisterStartupScript(this.Page, typeof(string), "OPEN_WINDOW", "window.open('ObjDetails.aspx', '_blank','scrollbars=yes,status=yes,toolbar=no,menubar=no,location=no,resizable=1,width=700,height=425,center=yes' );", true);

当我要存储并关闭详细信息弹出窗口时,我设置了将刷新 DS 调用 btnRefreshDS OnClick 事件的回发

    Session.Remove("EditObjectVar");
    StoreValuesOnObject();
    Session["EditObjectVar"] = editObject;
    ScriptManager.RegisterStartupScript(this.Page, GetType(), "Close Popup", String.Format("window.opener.__doPostBack('{0}', 'OnClick');window.close();", Session["BtnRefreshUniqueID"].ToString()), true);

而且,这是OnClick 事件

protected void btnRefresDS_Click(object sender, EventArgs e)
{
    try
    { 
        if (Session["EditObjectVar"] != null)
        {
            gv.DataSource = CurrentDS;
            gv.DataBind();
            Session.Remove("EditObjectVar");
        }
    }
    catch (Exception ee)
    {
        MyPage.Log(ee.StackTrace);
        MyPage.Log(ee.Message);
    }
}

鉴于,在 Session 变量上,它存储了对象内存位置而不是对象本身,我的 DS 上已经有了更新的对象(它也存储在 Session 上),所以我只需要分配 DS 和调用数据绑定。

希望这对任何人都有帮助!

【讨论】:

  • 如果您的服务器使用的是 SQL SessionState 而不是 ad-hoc,这将不可行!学到了很难的方式。您将需要调整 DS 以更新修改的对象或删除旧对象并存储新对象。然后你对数据进行数据绑定。
【解决方案2】:

我没有尝试跟踪所有内容,但这并不是因为您遗漏了“gv.DataBind();”在那里,是吗?我知道当您从 PC 应用程序来回切换到 Web 应用程序时会发生这种情况...

【讨论】:

  • 是的,我在代码上有一个.DataBind()。忘记在示例中添加它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多