This is a migrated thread and some comments may be shown as answers.

RadGrid is getting hide on postback due to execution of RadGrid any command...

1 Answer 222 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Tushar
Top achievements
Rank 1
Tushar asked on 03 Sep 2011, 08:03 AM
Hi,

RadGrid is getting hide after clicking of any command button either of Add New Item, Edit, Delete, Sorting, Paging. I'm using NeedDataSource event handler to bind grid. I've added sample code as below. 



ASPX Page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Inventory_Test" EnableEventValidation="false" %>
 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<html>
<head runat="server">
    <title>Enterprise Business Solutions --> Categories</title>
 
    <script type="text/javascript" src="../include/mainscript.js"></script>
 
</head>
<body id="bodyoverflow" onload="focus()">
 
    <script language="javascript" type="text/javascript">
        tb_loading(getLoadingMsg());
    </script>
 
    <form id="form1" runat="server">
    <asp:ScriptManager AsyncPostBackTimeout="600" ID="ScriptManager" runat="server">
    </asp:ScriptManager>
    <table width="100%" cellpadding="0" border="0" cellspacing="0">
        <tr class="HeaderRow">
            <td>
                <PTLUC:TMSHeader ObjNum="311" BOName="ItemMasterBO" runat="server" ID="HeaderCtrl"
                    ResourceName="">
                </PTLUC:TMSHeader>
            </td>
        </tr>
    </table>
    <div id="div-datagrid">
        <span class="reqField">Fields marked with an asterisk(<span style="color: Red">*</span>)
            are required.</span>
        <br />
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <telerik:RadDockLayout runat="server" ID="RadDockLayout1">
                    <table width="100%">
                        <tr>
                            <td style="vertical-align: top">
                                <telerik:RadDockZone ID="RadDockZone2" runat="server" Orientation="Vertical" Width="100%"
                                    MinHeight="400px">
                                    <telerik:RadDock ID="RadDock1" runat="server" Title="Grid" Width="100%"
                                        EnableRoundedCorners="true" Resizable="true" DockMode="Default" DockHandle="TitleBar"
                                        EnableDrag="true" ExpandText="Expand" ExpandedHeight="400" CollapseText="Collapse" >
                                        <Commands><telerik:DockExpandCollapseCommand /></Commands>
                                        <ContentTemplate>
                                            <telerik:RadGrid ID="gridFinancialYear" runat="server" AllowAutomaticDeletes="false"
                                                AllowAutomaticInserts="false" ShowFooter="true" PageSize="10" AllowAutomaticUpdates="false"
                                                AllowPaging="True" AutoGenerateColumns="False" OnItemUpdated="gridFinancialYear_ItemUpdated"
                                                OnItemDeleted="gridFinancialYear_ItemDeleted" OnItemDataBound="gridFinancialYear_ItemDataBound"
                                                OnItemInserted="gridFinancialYear_ItemInserted" OnDataBound="gridFinancialYear_DataBound"
                                                AllowSorting="true" OnDeleteCommand="gridFinancialYear_DeleteCommand" OnInsertCommand="gridFinancialYear_InsertCommand"
                                                OnNeedDataSource="gridFinancialYear_NeedDataSource" OnItemCommand="gridFinancialYear_ItemCommand"
                                                OnUpdateCommand="gridFinancialYear_UpdateCommand" Style="font-family: Verdana;
                                                font-size: 8pt;">
                                                <PagerStyle Mode="NextPrevAndNumeric" />
                                                <MasterTableView Width="70%" CommandItemDisplay="TopAndBottom" DataKeyNames="FIN_YEAR_ID"
                                                    HorizontalAlign="NotSet" EditMode="InPlace" AutoGenerateColumns="False">
                                                    <Columns>
                                                        <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
                                                            <ItemStyle CssClass="MyImageButton" />
                                                        </telerik:GridEditCommandColumn>
                                                        <telerik:GridTemplateColumn SortExpression="FROM_DATE" HeaderText="From" HeaderStyle-VerticalAlign="Top">
                                                            <ItemTemplate>
                                                                <PTLUC:TMSLabel Text='<%# Eval("FROM_DATE")%>' runat="server" ID="lblFromDate"></PTLUC:TMSLabel>
                                                            </ItemTemplate>
                                                            <EditItemTemplate>
                                                                <asp:TextBox Text='<%# Eval("FROM_DATE") %>' ID="txtFromDate" runat="server" Style="font-family: Verdana;
                                                                    font-size: 8pt; border-color: #7F9DB9;">
                                                                </asp:TextBox>
                                                            </EditItemTemplate>
                                                        </telerik:GridTemplateColumn>
                                                        <telerik:GridTemplateColumn SortExpression="TO_DATE" HeaderText="To" HeaderStyle-VerticalAlign="Top">
                                                            <ItemTemplate>
                                                                <PTLUC:TMSLabel Text='<%# Eval("TO_DATE")%>' runat="server" ID="lblToDate"></PTLUC:TMSLabel>
                                                            </ItemTemplate>
                                                            <EditItemTemplate>
                                                                <asp:TextBox Text='<%# Eval("TO_DATE") %>' ID="txtToDate" runat="server" Style="font-family: Verdana;
                                                                    font-size: 8pt; border-color: #7F9DB9;"></asp:TextBox>
                                                            </EditItemTemplate>
                                                        </telerik:GridTemplateColumn>
                                                        <telerik:GridCheckBoxColumn DataField="IS_LOCKED" UniqueName="IS_LOCKED" SortExpression="IS_LOCKED"
                                                            HeaderText="Lock" HeaderStyle-VerticalAlign="Top">
                                                        </telerik:GridCheckBoxColumn>
                                                    </Columns>
                                                </MasterTableView>
                                            </telerik:RadGrid>
                                        </ContentTemplate>
                                    </telerik:RadDock>
                                </telerik:RadDockZone>
                            </td>
                        </tr>
                    </table>
                </telerik:RadDockLayout>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    <PTLUC:PTLTextBox ID="txtId" Style="display: none" runat="server">
    </PTLUC:PTLTextBox>
    <PTLUC:PTLTextBox ID="txtsave" Style="display: none" runat="server"></PTLUC:PTLTextBox>
    <PTLUC:PTLTextBox ID="hidError" Style="display: none" runat="server"></PTLUC:PTLTextBox>
    <PTLUC:PTLTextBox ID="hidAction" Style="display: none" runat="server"></PTLUC:PTLTextBox>
    <PTLUC:PTLTextBox ID="hdnIsRawMaterial" Style="display: none" runat="server"></PTLUC:PTLTextBox>
    <asp:HiddenField runat="server" ID="hdnProfileValue" />
    </form>
 
    <script language="javascript" type="text/javascript">
        tb_remove();
    </script>
 
</body>
</html>


Code Behind:
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using PTLInventoryBO;
using PTLLibs;
using Telerik.Web.UI;
using PTLAdminBO;
using PTLAccountBO;
 
public partial class Inventory_Test : TMSBasePage
{
    int orgId = 1;
 
    protected override void Initialize()
    {
        try
        {
            base.myBO = new ItemMasterBO(base.UserId);
            this.PageID = "Test";
            this.ObjNum = 313;
            this.HeaderCtrl.ObjNum = 313;
            this.myBO.Title = "Products";
            this.TxtID = this.txtId;
            this.TxtSave = this.txtsave;
            this.ObjNum = 301;
            this.myBO.PrimaryKeyValue = Int32.Parse(Request.QueryString["pkid"].ToString());
            FindPageControls();
            base.Initialize();
        }
        catch (Exception ex)
        {
 
        }
    }
 
    private void FindPageControls()
    {
 
    }
 
    protected override void AfterSaveAction()
    {
        hidError.Text = HidErrors.Text;
        base.AfterSaveAction();
    }
 
    protected override void AfterDeleteAction()
    {
        this.hidError.Text = HidErrors.Text.ToString();
        base.AfterDeleteAction();
    }
 
    public override void Save()
    {
        base.Save();
    }
 
    protected override void BindDataToPage()
    {
        try
        {
            base.BindDataToPage();
        }
        catch (Exception ex)
        {
 
        }
    }
 
    public override void BindDataFromPage()
    {
        try
        {
            PageData["ITEM_ID"] = txtId.Text.ToString();
            base.BindDataFromPage();
        }
        catch (Exception ex)
        {
        }
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    public void gridFinancialYear_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
    {
        try
        {
            gridFinancialYear.DataSource = gridFinancialYear.MasterTableView.DataSource = GetData();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    public DataTable GetData()
    {
        try
        {
            FinancialYearBO objFinYear = new FinancialYearBO(this.UserId);
            if (Session["IsLogMode"] != null && Session["IsLogMode"].ToString() == "true")
                objFinYear.UpdateMode = true;
            else
                objFinYear.UpdateMode = false;
            DataTable dtFinYear = objFinYear.GetFinYear(orgId);
            return dtFinYear;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    private void DisplayMessage(string text)
    {
        gridFinancialYear.Controls.Add(new LiteralControl(string.Format("<span style='color:red'>{0}</span>", text)));
    }
 
    private void SetMessage(string message)
    {
        gridMessage = message;
    }
 
    private string gridMessage = null;
 
    protected void gridFinancialYear_DataBound(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(gridMessage))
        {
            DisplayMessage(gridMessage);
        }
    }
 
    protected void gridFinancialYear_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
    {
        try
        {
            GridEditableItem item = (GridEditableItem)e.Item;
            String id = item.GetDataKeyValue("FIN_YEAR_ID").ToString();
 
            if (e.Exception != null)
            {
                e.KeepInEditMode = true;
                e.ExceptionHandled = true;
                SetMessage("Financial Year with ID " + id + " cannot be updated. Reason: " + e.Exception.Message);
            }
            else
            {
                SetMessage("Financial Year with ID " + id + " is updated!");
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    protected void gridFinancialYear_ItemInserted(object source, GridInsertedEventArgs e)
    {
        try
        {
            if (e.Exception != null)
            {
                e.ExceptionHandled = true;
                SetMessage("Unable to insert. Reason: " + e.Exception.Message);
            }
            else
            {
                //SetMessage("New product is inserted!");
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    protected void gridFinancialYear_ItemDeleted(object source, GridDeletedEventArgs e)
    {
        try
        {
            GridDataItem dataItem = (GridDataItem)e.Item;
            String id = dataItem.GetDataKeyValue("FIN_YEAR_ID").ToString();
 
            if (e.Exception != null)
            {
                e.ExceptionHandled = true;
                SetMessage("Financial Year with ID " + id + " cannot be deleted. Reason: " + e.Exception.Message);
            }
            else
            {
                SetMessage("Financial Year with ID " + id + " is deleted!");
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    protected void gridFinancialYear_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.EditCommandName)
        {
            gridFinancialYear.MasterTableView.IsItemInserted = false;
        }
        if (e.CommandName == RadGrid.InitInsertCommandName)
        {
            gridFinancialYear.MasterTableView.ClearEditItems();
        }
    }
 
    protected void gridFinancialYear_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        try
        {
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                GridEditableItem item = (GridEditableItem)e.Item;
 
                #region General Declarations for Controls in Edit Mode
                TextBox txtFromDate = item.FindControl("txtFromDate") as TextBox;
                TextBox txtToDate = item.FindControl("txtToDate") as TextBox;
 
                #endregion
                if (txtFromDate.Text != "")
                {
                    txtFromDate.Enabled = true;
                    txtToDate.Enabled = true;
                    if (((CheckBox)item["IS_LOCKED"].Controls[0]).Checked)
                    {
                        ((CheckBox)item["IS_LOCKED"].Controls[0]).Enabled = true;
                        ((ImageButton)item["EditCommandColumn"].Controls[0]).Visible = false;
                    }
                }
                else
                    ((CheckBox)item["IS_LOCKED"].Controls[0]).Enabled = true;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    protected void gridFinancialYear_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        //Get the GridDataItem of the RadGrid    
        GridDataItem item = (GridDataItem)e.Item;
        //Get the primary key value using the DataKeyValue.    
        string FIN_YEAR_ID = item.OwnerTableView.DataKeyValues[item.ItemIndex]["FIN_YEAR_ID"].ToString();
        try
        {
            StockDetailBO objStockBO = new StockDetailBO(this.UserId);
            objStockBO.DeleteStockDetailById(Int32.Parse(FIN_YEAR_ID));
            e.Item.Edit = false;
        }
        catch (Exception ex)
        {
            gridFinancialYear.Controls.Add(new LiteralControl("Unable to delete. Reason: " + ex.Message));
            e.Canceled = true;
        }
 
    }
 
    protected void gridFinancialYear_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        Guid gmsg = Guid.NewGuid();
        string errmsg;
        //Get the GridEditableItem of the RadGrid    
        GridEditableItem editedItem = e.Item as GridEditableItem;
        //Get the primary key value using the DataKeyValue.    
        string FIN_YEAR_ID = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["FIN_YEAR_ID"].ToString();
        try
        {
            FinancialYearBO objFinYear = new FinancialYearBO(this.UserId);
 
            objFinYear.FinId = Int32.Parse(FIN_YEAR_ID);
            objFinYear.OrgId = orgId;
            objFinYear.FromDate = ((TextBox)editedItem.FindControl("txtFromDate")).Text.ToString();
            objFinYear.ToDate = ((TextBox)editedItem.FindControl("txtToDate")).Text.ToString();
            if (((CheckBox)editedItem["IS_LOCKED"].Controls[0]).Checked)
            {
                DateTime fromDate = Convert.ToDateTime(((TextBox)editedItem.FindControl("txtFromDate")).Text.ToString());
                DateTime toDate = Convert.ToDateTime(((TextBox)editedItem.FindControl("txtToDate")).Text.ToString());
                if ((fromDate.ToString("MM/dd/yyyy").Equals(this.Session["FromDate"])) && (toDate.ToString("MM/dd/yyyy").Equals(this.Session["ToDate"])))
                {
                    errmsg = "alert('You cannot lock the current financial year.');";
                    ScriptManager.RegisterStartupScript(gridFinancialYear, gridFinancialYear.GetType(), gmsg.ToString(), errmsg, true);
                }
 
                else
                {
                    objFinYear.IsLocked = ((CheckBox)editedItem["IS_LOCKED"].Controls[0]).Checked;
                    if (objFinYear.FromDate != "" && objFinYear.ToDate != "")
                    {
                        int i;
                        i = DateTime.Compare(fromDate, toDate);
                        if (i > 0)
                        {
                            errmsg = "alert('From Date should not be less than To Date.');";
                            ScriptManager.RegisterStartupScript(gridFinancialYear, gridFinancialYear.GetType(), gmsg.ToString(), errmsg, true);
                        }
                        else
                        {
                            string message = "";
                            if ((message = objFinYear.CheckYear(1)) == "")
                            {
                                //Updating the Financial year details
                                int id = objFinYear.Save();
                                AccountMasterBO objAcc = new AccountMasterBO(this.UserId);
                                objAcc.UpdateAccountBalances(id, orgId, -1);
                            }
                            else
                            {
                                errmsg = "alert('" + message + "');";
                                ScriptManager.RegisterStartupScript(gridFinancialYear, gridFinancialYear.GetType(), gmsg.ToString(), errmsg, true);
                            }
                            e.Item.Edit = false;
                        }
 
                    }
                    else
                    {
                        errmsg = "alert('Date fields cannot be blank.');";
                        ScriptManager.RegisterStartupScript(gridFinancialYear, gridFinancialYear.GetType(), gmsg.ToString(), errmsg, true);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            gridFinancialYear.Controls.Add(new LiteralControl("Unable to update. Reason: " + ex.Message));
            e.Canceled = true;
        }
 
    }
 
    protected void gridFinancialYear_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        //Get the GridDataInsertItem of the RadGrid    
        GridDataInsertItem insertedItem = (GridDataInsertItem)e.Item;
        Guid gmsg = Guid.NewGuid();
        string errmsg;
        try
        {
            FinancialYearBO objFinYear = new FinancialYearBO(this.UserId);
            objFinYear.FinId = -1;
            objFinYear.OrgId = orgId;
            objFinYear.FromDate = ((TextBox)insertedItem.FindControl("txtFromDate")).Text.ToString();
            objFinYear.ToDate = ((TextBox)insertedItem.FindControl("txtToDate")).Text.ToString();
            objFinYear.IsLocked = ((CheckBox)insertedItem["IS_LOCKED"].Controls[0]).Checked;
            if (objFinYear.FromDate != "" && objFinYear.ToDate != "")
            {
                DateTime fromDate = Convert.ToDateTime(((TextBox)insertedItem.FindControl("txtFromDate")).Text.ToString());
                DateTime toDate = Convert.ToDateTime(((TextBox)insertedItem.FindControl("txtToDate")).Text.ToString());
                int i;
                i = DateTime.Compare(fromDate, toDate);
                if (i > 0)
                {
                    errmsg = "alert('To Date cannot be earlier than From Date.');";
                    ScriptManager.RegisterStartupScript(gridFinancialYear, gridFinancialYear.GetType(), gmsg.ToString(), errmsg, true);
                }
                else
                {
                    string message = "";
                    if ((message = objFinYear.CheckYear(0)) == "")
                    {
                        int fid = -1;
                        //Saving the Financial year details
                        if ((fid = objFinYear.Save()) == -1)
                        {
                            errmsg = "alert('Duplicate Financial year. Please enter unique year.');";
                            ScriptManager.RegisterStartupScript(gridFinancialYear, gridFinancialYear.GetType(), gmsg.ToString(), errmsg, true);
                        }
                        else
                        {
                            //upadting the opening balances for the new year
                            AccountMasterBO objAcc = new AccountMasterBO(this.UserId);
                            objAcc.InsertAccountBalancesForNewYear(fid, orgId);
                        }
                    }
                    else
                    {
                        errmsg = "alert('" + message + "');";
                        ScriptManager.RegisterStartupScript(gridFinancialYear, gridFinancialYear.GetType(), gmsg.ToString(), errmsg, true);
                    }
                    e.Item.Edit = false;
                }
            }
            else
            {
                errmsg = "alert('Date fields cannot be blank..');";
                ScriptManager.RegisterStartupScript(gridFinancialYear, gridFinancialYear.GetType(), gmsg.ToString(), errmsg, true);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
 
    }
}


I've also found the reason of this issue its because of the query string of the page on which this grid is implemented. When grid item is rendered on form then every link item is taking same query string as of page's query string. This issue is not getting occurred when I run above code without using query string.

Please help me...

1 Answer, 1 is accepted

Sort by
0
Tsvetina
Telerik team
answered on 07 Sep 2011, 03:08 PM
Hello Tushar,

Have you tried temporarily removing AJAX to confirm that no exceptions are thrown from your code? Also, try simply assigning the DataSource to the grid control inside NeedDataSource, you do not need the MasterTableView's DataSource assigned, too.

Let us know in case the issue persists.

Greetings,
Tsvetina
the Telerik team

Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

Tags
Grid
Asked by
Tushar
Top achievements
Rank 1
Answers by
Tsvetina
Telerik team
Share this question
or