更新面板的问题

本文关键字:问题 更新 | 更新日期: 2023-09-27 18:30:55

我有一个问题,例如,当我删除一个项目时,它会从数据库中删除,很好地使用 bindGridView(),但不刷新屏幕...我做错了什么?

另一个问题是,例如,当我删除一个项目时,我想显示成功消息,但也没有使用更新面板刷新。

是同样的问题这是我的代码:

<asp:UpdatePanel ID="UpdatePanelListaUsers" runat="server" UpdateMode="Always">
                            <ContentTemplate>
                                <asp:GridView ID="gridviewListUsers" runat="server" AutoGenerateColumns="false" OnRowCreated="OnRowCreated"
                                AllowPaging="True" AllowSorting="True" OnSorting="OnSort" DataKeyNames="Id" PageSize="2"
                                CssClass="cssTable" BorderWidth="0" Width="900px" AlternatingRowStyle-CssClass="alternate-row"
                                OnRowCommand="gridviewListUsers_RowCommand" 
                                EmptyDataText="Não existe utilizadores..." 
                                    onpageindexchanging="gridviewListUsers_PageIndexChanging">
                                <PagerStyle HorizontalAlign="Right" Font-Bold="true" Font-Size="X-Large" ForeColor="black" />
                                <PagerSettings Mode="Numeric" />
                                <Columns>
                                    <asp:BoundField HeaderStyle-CssClass="table-header-repeat line-left minwidth-1" HeaderText="Nome"
                                        DataField="Name" SortExpression="Name" />
                                    <asp:BoundField HeaderStyle-CssClass="table-header-repeat line-left minwidth-1" HeaderText="Username"
                                        DataField="Username" SortExpression="Username" />
                                    <asp:BoundField HeaderStyle-CssClass="table-header-repeat line-left" HeaderText="Email"
                                        DataField="Email" SortExpression="Email" />
                                    <asp:TemplateField ItemStyle-CssClass="options-width" HeaderStyle-CssClass="table-header-options line-left">
                                        <HeaderTemplate>
                                            <a href="">Opções</a></HeaderTemplate>
                                        <ItemTemplate>
                                            <asp:LinkButton ID="lnkEdit" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' CssClass="icon-1 info-tooltip"
                                                CommandName="edit" ToolTip="Editar" runat="server"></asp:LinkButton>
                                            <asp:LinkButton ID="lnkDelete" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' CssClass="icon-2 info-tooltip"
                                                CommandName="delete" ToolTip="Remover" runat="server"></asp:LinkButton>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                            </ContentTemplate>
                            </asp:UpdatePanel>

<asp:UpdatePanel ID="UpdatePanelMensagens" runat="server" UpdateMode="Always">
                            <ContentTemplate>
                            <asp:Panel ID="pnlMessageRed" Visible="false" runat="server">
                                <!--  start message-red -->
                                <div id="message-red">
                                    <table border="0" width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td class="red-left">
                                                Erro. Ficou gravado a informação do erro, tente novamente
                                            </td>
                                            <td class="red-right">
                                                <a class="close-red">
                                                    <img src="../images/table/icon_close_red.gif" alt="" /></a>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                <!--  end message-red -->
                            </asp:Panel>
                            <asp:Panel ID="pnlMessageBlue" Visible="false" runat="server">
                                <!--  start message-blue -->
                                <div id="message-blue">
                                    <table border="0" width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td class="blue-left">
                                                <asp:Label ID="lblSucesso" runat="server"></asp:Label>
                                            </td>
                                            <td class="blue-right">
                                                <a class="close-blue">
                                                    <img src="../images/table/icon_close_blue.gif" alt="" /></a>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                <!--  end message-blue -->
                            </asp:Panel>
                            </ContentTemplate>
                            </asp:UpdatePanel>

这是网格视图代码

private void bindGridView()
    {
        String strSort = String.Empty;
        if (null != m_strSortExp &&
            String.Empty != m_strSortExp)
        {
            strSort = String.Format("{0} {1}", m_strSortExp, (m_SortDirection == SortDirection.Descending) ? "DESC" : "ASC");
        }
        DataView dv = new DataView(m_dsUsers.Tables[0], String.Empty, strSort, DataViewRowState.CurrentRows);
        gridviewListUsers.DataSource = dv;
        gridviewListUsers.DataBind();
        UpdatePanelListaUsers.Update();
    }
protected void OnSort(object sender, GridViewSortEventArgs e)
    {
        // There seems to be a bug in GridView sorting implementation. Value of
        // SortDirection is always set to "Ascending". Now we will have to play
        // little trick here to switch the direction ourselves.
        if (String.Empty != m_strSortExp)
        {
            if (String.Compare(e.SortExpression, m_strSortExp, true) == 0)
            {
                m_SortDirection =
                    (m_SortDirection == SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            }
        }
        ViewState["_Direction_"] = m_SortDirection;
        ViewState["_SortExp_"] = m_strSortExp = e.SortExpression;
        this.bindGridView();
    }
    void AddSortImage(GridViewRow headerRow)
    {
        Int32 iCol = GetSortColumnIndex(m_strSortExp);
        if (-1 == iCol)
        {
            return;
        }
        // Create the sorting image based on the sort direction.
        Image sortImage = new Image();
        if (SortDirection.Ascending == m_SortDirection)
        {
            sortImage.ImageUrl = "~/images/table/dwn.gif";
            sortImage.AlternateText = "Ordem Ascendente";
        }
        else
        {
            sortImage.ImageUrl = "~/images/table/up.gif";
            sortImage.AlternateText = "Ordem Descendente";
        }
        // Add the image to the appropriate header cell.
        headerRow.Cells[iCol].Controls.Add(sortImage);
    }
    // This is a helper method used to determine the index of the
    // column being sorted. If no column is being sorted, -1 is returned.
    int GetSortColumnIndex(String strCol)
    {
        foreach (DataControlField field in gridviewListUsers.Columns)
        {
            if (field.SortExpression == strCol)
            {
                return gridviewListUsers.Columns.IndexOf(field);
            }
        }
        return -1;
    }
    protected void gridviewListUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "delete")
        {
            try
            {
                //obter o id
                int index = int.Parse((string)e.CommandArgument);
                string key = gridviewListUsers.DataKeys[index]["Id"].ToString();
                //apagar o utilizador
                Project_BLL.Users.RemoveUser(Convert.ToInt32(key));
                //mensagem de sucesso
                pnlMessageRed.Visible = false;
                pnlMessageBlue.Visible = true;
                lblSucesso.Text = "Utilizador adicionado com sucesso. A reencaminhar...";
                //força o update dos users, e nao da cache
                bindGridView();
                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                LinkButton lb = (LinkButton)row.FindControl("lnkDelete");
                if (lb != null)
                {
                    ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(lb);
                }
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alertUser", "alert('deleted');", true);
            }
            catch (Exception er)
            {
                pnlMessageRed.Visible = true;
                pnlMessageBlue.Visible = false;
            }
        }
        else if (e.CommandName == "edit")
        {
            try
            {
                int index = int.Parse((string)e.CommandArgument);
                string key = gridviewListUsers.DataKeys[index]["Id"].ToString();
                Response.Redirect("EditarUtilizador.aspx?id=" + key);
            }
            catch (Exception)
            {
                pnlMessageRed.Visible = true;
                pnlMessageBlue.Visible = false;
            }
        }
    }
    protected void gridviewListUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridviewListUsers.PageIndex = e.NewPageIndex;
        gridviewListUsers.SelectedIndex = -1;
        bindGridView(); // Call bind here
    }

更新面板的问题

第二个问题:从代码隐藏注册脚本

protected void gridviewListUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "delete")
        {
            //your code
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertUser", "alert('deleted');", true);
        }
    }

当你确定你的循环进入CommandName="delete"时,javascript警报方法绝对应该调用。

第一个问题:在 UpdatePanel 中设置 UpdateMode="Conditional",并在代码隐藏中使用以下方法:

public UpdatePanelUpdateMode UpdateMode
{
    get { return this.UpdatePanelListaUsers.UpdateMode; }
    set { this.UpdatePanelListaUsers.UpdateMode = value; }
}
public void Update()
{
    this.UpdatePanelListaUsers.Update();
    //your girdview bind method.
    bindGridView()
}

现在只需调用bindGridView()任何你想要获得刷新更新面板的地方。

刚刚将 CommandName 更改为 myEdit 和 myDelete(就像 Ashwini Verma 之前建议的那样),现在它可以工作了。

然后我用谷歌搜索它找到原因,似乎这些词是保留的

http://www.mindfiresolutions.com/Issue-with-OnRowCommand-event-of-GridView-while-using-reserve-words-in-CommandName-property-935.php