Telerik Forums
UI for ASP.NET AJAX Forum
3 answers
924 views
Hi,

I have a radgrid in my .aspx page. I'm having a checkbox inside the  GridTemplateColumn.  On the checkbox onclick event I am calling the javascript function  chkRowSelection(this).   In that function I need to get the values of the radgrid ClientDataKeyNames="SRC,SER,BAND,XLA,XLG,RGN,STT,EIP,SVC,FRQ,FTA"  for the row checked. Could you please help me to achieve this.

<

 

telerik:RadGrid ID="grdResult" runat="server" Width="900px"

 

 

AllowMultiRowSelection="True" AllowSorting="True" Height="400px"

 

 

style="margin-right: 1px" Skin="WebBlue" GridLines="None" AllowPaging="true" PageSize="100">

 

 

<PagerStyle Position="Top" />

 

 

<MasterTableView AllowPaging="true" AutoGenerateColumns="true" AllowMultiColumnSorting="true" ClientDataKeyNames="SRC,SER,BAND,XLA,XLG,RGN,STT,EIP,SVC,FRQ,FTA" Font-Size="Smaller" PageSize="100" >

 

 

<Columns>

 

 

<telerik:GridTemplateColumn UniqueName="SEL">

 

 

<HeaderTemplate>

 

 

<asp:CheckBox runat="server" ID="ChkAll" ToolTip="Click to select all" onclick="javascript:SelectAllCheckboxes(this);" />

 

 

</HeaderTemplate>

 

 

<HeaderStyle Width="20px" />

 

 

<ItemTemplate>

 

 

<asp:CheckBox runat="server" ID="SEL" onclick="javascript:chkRowSelection(this);" />

 

 

</ItemTemplate>

 

 

<ItemStyle Width="20px" />

 

 

</telerik:GridTemplateColumn>

 

 

</Columns>

 

 

<ItemStyle Wrap="false" />

 

 

<HeaderStyle Wrap="False" />

 

 

</MasterTableView>

 

 

<HeaderStyle Wrap="False" />

 

 

<ClientSettings ReorderColumnsOnClient="true" EnableRowHoverStyle="False" AllowColumnsReorder="true" >

 

 

<Scrolling AllowScroll="True" UseStaticHeaders="true" />

 

 

<Selecting AllowRowSelect="true" />

 

 

<Resizing EnableRealTimeResize="true" ResizeGridOnColumnResize="true" AllowColumnResize="true"/>

 

 

<ClientEvents OnRowContextMenu="grdResult_RowSelected" OnRowClick="RowClicked" />

 

 

</ClientSettings>

 

 

<Headerstyle Width="65px" />

 

 

<PagerStyle Mode="NextPrevAndNumeric" ></PagerStyle>

 

</

 

telerik:RadGrid>

javascript:

 

 

function chkRowSelection(chkBox)
{
 // need to get the values of the ClientDataKeyNames="SRC,SER,BAND,XLA,XLG,RGN,STT,EIP,SVC,FRQ,FTA"  for the selected row in this function.
}

Thanks,
Raji

 

Shinu
Top achievements
Rank 2
 answered on 28 Jan 2013
1 answer
72 views
I'm working on  a Hierachical RadGrid which is enclosed in an  asp UpdatePanel, and I need to customize it in such a way that - Only the parent rows should be rendered first(the query corresponding to this fetches only the parent rows from the database), and then on the expand button click - the 'Id' corresponding to the row is send via ajax and a different query fetches the child data corresponding to only the selected row. Currently I'm invoking an external ajax request through a jquery call from ClientEvents-OnRowClick in the ClientSettings of the grid. Now I'm unable to fill data into the child table from the ajax response using jquery. Is there an easier way to go about it? That is there an inbuilt function to use 2 different queries - one to get the parent rows and the other to get the child row corresponding to the parent row that is clicked.

Thanks in advance.
Andrey
Telerik team
 answered on 28 Jan 2013
1 answer
96 views
Hello,

I've a standard radtreeview control populated on the server side by sql datas. Depending on the node type i set the node ForeColor property. When i do a client-side drag/drop i'm loosing the node color. It's probably a newbee question but how can i keep the original node color ?

Thanks in advance for the help.
Denis
Clyde
Top achievements
Rank 1
 answered on 28 Jan 2013
1 answer
68 views
I am cross-posting in Grid and Ajax forums due to not know which forum would be most appropriate.

I've created my page following this example:
http://demos.telerik.com/aspnet-ajax/grid/examples/dataediting/clienteditbatchupdates/defaultcs.aspx

In this demo the grid row's unique ids are the first column called Product ID which is displayed in the gird. For my application each row's unique id is a GUID which I do NOT want displayed. If I set the visibility of this column to false the ajax does not work because it does not have a unqiue id to pass to the code-behind functions. If I set the visibility to true all works.  From this example it appears I must display the unique id column for the code to work.

How can I not display the GUID but still make it available to the ajax functions to pass to the code-behind file functions?
Jayesh Goyani
Top achievements
Rank 2
 answered on 27 Jan 2013
2 answers
227 views
We are trying to reduce the grid ViewState using a PageStatePersister and database.
Everything is working fine also using the advanced data-binding except for the exporting functionality (xls, pdf or csv) does not matter the format.

The exported file is correct, we ignore the paging and the whole data is saved correctly, but if we click for example on the pager, the RadGrid loses the paging and also the excel button on the command items, this happens only if we have already exported a file.

The same code without the PageStatePersister works fine.

We can't figure out where the error is, do you have any clues?

public class SqlPageStatePersister : PageStatePersister
  {
    private const string VSKEY = "__VSKEY";
    private const string VSPREFIX = "VIEWSTATE_";
 
    private static readonly PageViewStateRepository Repository = new PageViewStateRepository();
 
    public SqlPageStatePersister(Page page)
      : base(page)
    {
    }
 
    public override void Load()
    {
      if (!Page.IsPostBack) return;
 
      string vsKey = Page.Request.Form[VSKEY];
 
      // Sanity Checks
      if (string.IsNullOrEmpty(vsKey)) throw new ViewStateException();
      if (!vsKey.StartsWith(VSPREFIX)) throw new ViewStateException();
 
      IStateFormatter frmt = StateFormatter;
      string state = GetViewState(vsKey);
 
      if (string.IsNullOrEmpty(state)) return;
 
      var statePair = frmt.Deserialize(state) as Pair;
 
      if (statePair == null) return;
 
      ViewState = statePair.First;
      ControlState = statePair.Second;
    }
 
    public override void Save()
    {
      if (Page.Session == null)
        throw new InvalidOperationException("Session is required for SqlPageStatePersister (SessionID -> Key)");
 
      if (ViewState != null || ControlState != null)
      {
        string vsKey;
 
        if (!Page.IsPostBack)
        {
          string sessionId = Page.Session.SessionID;
          string pageUrl = Page.Request.Path;
          vsKey = string.Format("{0}{1}_{2}_{3}", VSPREFIX, pageUrl, sessionId, DateTime.Now.Ticks);
        }
        else
        {
          vsKey = Page.Request.Form[VSKEY];
          if (string.IsNullOrEmpty(vsKey)) throw new ViewStateException();
        }
 
        IStateFormatter frmt = StateFormatter;
        string state = frmt.Serialize(new Pair(ViewState, ControlState));
        StoreViewState(vsKey, state);
 
        Page.Cache.Add(vsKey, vsKey, null, DateTime.Now.AddMinutes(Page.Session.Timeout),
                       Cache.NoSlidingExpiration, CacheItemPriority.Low, ViewStateCacheRemoveCallback);
        Page.ClientScript.RegisterHiddenField(VSKEY, vsKey);
      }
    }
 
    #region Database
 
    private static void StoreViewState(string key, string viewStateData)
    {
      var item = new PageViewState {ID = key, Value = viewStateData, LastUpdatedOn = DateTime.Now};
      Repository.InsertOrUpdate(item);
    }
 
    private static string GetViewState(string key)
    {
      PageViewState vs = Repository.Select(key);
      if (vs != null)
        return vs.Value;
      return string.Empty;
    }
 
    private static void ViewStateCacheRemoveCallback(string key, object value, CacheItemRemovedReason reason)
    {
      Repository.Delete(Repository.Select(key));
    }
 
    #endregion
  }
}

public class SqlPageAdapter : PageAdapter
{
  public override PageStatePersister GetStatePersister()
  {
    return new SqlPageStatePersister(Page);
  }
}

<browsers>
  <browser refID="Default">
    <controlAdapters>
      <adapter
          controlType="System.Web.UI.Page"
          adapterType="DataValidator.PageState.SqlPageAdapter" />
    </controlAdapters>
  </browser>
</browsers>

<telerik:RadGrid ID="RadGrid1" runat="server" AllowFilteringByColumn="True" AllowPaging="True"
    CellSpacing="0" GridLines="None" OnNeedDataSource="NeedDataSource" AllowSorting="True"
    AutoGenerateColumns="False" OnItemDataBound="RadGrid1_ItemDataBound" EnableViewState="True"
    OnItemCommand="RadGrid1_ItemCommand">
    <MasterTableView DataKeyNames="ID" PageSize="20" CommandItemDisplay="Top" EnableViewState="True">
        <CommandItemSettings ShowAddNewRecordButton="false" ShowExportToExcelButton="true">
        </CommandItemSettings>
        <Columns>
            <telerik:GridBoundColumn DataField="Version" HeaderText="Version" SortExpression="Version"
                UniqueName="Version" FilterControlWidth="95px" />
            <telerik:GridDateTimeColumn DataField="Date" HeaderText="Date" SortExpression="Date"
                UniqueName="Date" FilterControlWidth="95px" PickerType="DatePicker" EnableTimeIndependentFiltering="true" />
            <telerik:GridBoundColumn DataField="Level" HeaderText="Level" SortExpression="Level"
                UniqueName="Level" FilterControlWidth="95px" />
            <telerik:GridBoundColumn DataField="Message" HeaderText="Type" SortExpression="Message"
                UniqueName="Message" FilterControlWidth="95px" />
            <telerik:GridBoundColumn DataField="Exception" HeaderText="Message" SortExpression="Exception"
                UniqueName="Exception">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="UserName" HeaderText="UserName" SortExpression="UserName"
                UniqueName="UserName" FilterControlWidth="95px" />
            <telerik:GridBoundColumn DataField="Page" HeaderText="Page" SortExpression="Page"
                UniqueName="Page" FilterControlWidth="95px" />
        </Columns>
    </MasterTableView>
    <ExportSettings ExportOnlyData="true" IgnorePaging="true" OpenInNewWindow="true">
        <Excel Format="Biff"></Excel>
    </ExportSettings>
    <FilterMenu EnableImageSprites="False">
    </FilterMenu>
    <PagerStyle Mode="NumericPages"></PagerStyle>
</telerik:RadGrid>

namespace DataValidator._uc
{
  public partial class LogCtrl : UserControlHelper, IGridUserControl
  {
    protected void Page_Load(object sender, EventArgs e)
    {
    }
 
    #region Implementation of IGridUserControl
 
    public void NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
      var lr = new LogRepository();
      RadGrid1.DataSource = lr.Select();
    }
 
    public void UpdateCommand(object sender, GridCommandEventArgs e)
    {
    }
 
    public void DeleteCommand(object sender, GridCommandEventArgs e)
    {
    }
 
    public void InsertCommand(object sender, GridCommandEventArgs e)
    {
    }
 
    #endregion
 
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
      if (e.Item is GridDataItem)
      {
        var log = (Log) e.Item.DataItem;
        if (log != null)
        {
          string message = log.Exception;
          if (message.Length > 100)
            message = string.Format("{0}...", message.Substring(0, 46));
          e.Item.Cells[6].Wrap = false;
          e.Item.Cells[6].ToolTip = log.Exception;
          e.Item.Cells[6].Text = message;
        }
      }
    }
 
    protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
      if (e.CommandName == RadGrid.ExportToExcelCommandName)
      {
        PageHelper.Exporting = true;
      }
    }
  }
}
Luca
Top achievements
Rank 1
 answered on 26 Jan 2013
1 answer
97 views
After doing about a day of searching around the web, these forums, and co-workers that have done similar applications as the one I'm currently tasked with, I'm forced to start a thread for help.

My issue: I'm using the Telerik DynamicRadGrid control in a DynamicData 4.0 web application and am able to use [Display(Order=-1)] in order to position my ForeignKey columns for a specific table at in a specific order in the INSERT and EDIT templates, but the ordering is not reflected in the DynamicRadGrid column ordering. I need to move a column from the far right (end) of the column listing in my DynamicRadGrid to the far left (start) of the column listing in my DynamicRadGrid control.

The DynamicRadGrid control in my DynamicData PageTemplate ListDetails.aspx file:
<dynamic:DynamicRadGrid ID="RadGrid1" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="false"
                PageSize="15" PagerStyle-Mode="NextPrevAndNumeric" runat="server" DataSourceID="GridDataSource"
                AllowAutomaticUpdates="true" AllowAutomaticInserts="true" OnItemCommand="RadGrid1_ItemCommand"
                OnItemDataBound="RadGrid1_ItemDataBound " AllowAutomaticDeletes="true" OnPageIndexChanged="RadGrid1_PageIndexChanged"
                OnDataBound="RadGrid1_DataBound">
                <ExportSettings ExportOnlyData="true" IgnorePaging="true" Excel-Format="ExcelML"
                    OpenInNewWindow="true">
                </ExportSettings>
                <MasterTableView CommandItemDisplay="Top" UseAllDataFields="true">
                    <CommandItemSettings ShowAddNewRecordButton="false" ShowExportToExcelButton="true" />
                </MasterTableView>
                <ClientSettings EnablePostBackOnRowClick="true">
                    <Selecting AllowRowSelect="true" />
                </ClientSettings>
            </dynamic:DynamicRadGrid>
            <asp:EntityDataSource ID="GridDataSource" runat="server" EnableDelete="true" EnableUpdate="true" />
            <asp:QueryExtender ID="GridQueryExtender" TargetControlID="GridDataSource" runat="server">
                <asp:DynamicFilterExpression ControlID="FilterRepeater" />
            </asp:QueryExtender>


The control is populated via the Page_Init() in the code behind:
protected void Page_Init(object sender, EventArgs e)
 {
     table = DynamicDataRouteHandler.GetRequestMetaTable(Context);
     RadGrid1.SetMetaTable(table, table.GetColumnValuesFromRoute(Context));
     FormView1.SetMetaTable(table);
     GridDataSource.EntityTypeFilter = table.EntityType.Name;
     DetailsDataSource.EntityTypeFilter = table.EntityType.Name;
 }

The [Display(Order=-1)] code is found in my PartialModelClasses Class and actually works when viewing/editing a specific record on an individual basis and not in the DynamicRadGrid control, which leads me to believe that the issue lies in support of the feature in the Telerik control and not in my code.

Any thoughts, ideas, or input would be greatly appreciated.
Wade
Top achievements
Rank 1
 answered on 25 Jan 2013
6 answers
339 views
Hi Telerik,

How to disable "previous & first page" arrow buttons on page 1 and "next & last page" arrows when on last page?
Also disabling all arrows when row count is less than the page size?

Appreciate your help. Thanks!
Bill
Top achievements
Rank 1
 answered on 25 Jan 2013
5 answers
251 views
I'm trying to use RadDatePicker in Visual Web Part. The problem was when I tried to call it in .vb (let's say its ID is radDate1), it did not exist in IntelliSense. Seeming like it's not recognized. 

TestWebPart.ascx

..
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
        <telerik:RadDatePicker ID="radDate1" Runat="server" AutoPostBack="false">                           
            <DateInput DateFormat="MM/dd/yyyy" />                   
        </telerik:RadDatePicker>
..

TestWebPart.ascx.vb

Private
Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
     radDate1  <--- not found in IntelliSense
End Sub

web.config
<SafeControls>
...
<SafeControl Assembly="Telerik.Web.UI, Version=2010.1.309.20, Culture=neutral, PublicKeyToken=121fae78165ba3d4" Namespace="Telerik.Web.UI" TypeName="*" Safe="True" SafeAgainstScript="False" />
...
</SafeControls>
...
<assemblies>
...
<add assembly="Telerik.Web.UI, Version=2010.1.309.20, Culture=neutral, PublicKeyToken=121fae78165ba3d4" />
...
</assemblies>

Please advise

Thanks
Brew

Bob
Top achievements
Rank 1
 answered on 25 Jan 2013
2 answers
126 views
I have a dll project in that added the following methods to create RadGrid dynamically

this method will be called inside a ascx control to build the grid
If I use Telerik.Web.UI.dll 2012.2.607.40 version ItemCommand evant firing for InitInsert, PerformInsert, Update and Delete
But If I use Telerik.Web.UI, Version=2011.1.519.40 it is not firing all the events Only InitInsert is working
How to Solve this.

    #region CreateRadGrid

        public Control CreateRadGrid(BusinessProperty property, bool readOnly)
        {
            bool addEnabled = (property.Description.IndexOf("__MIADD__", StringComparison.Ordinal) != -1);
            bool editEnabled = (property.Description.IndexOf("__MIEDIT__", StringComparison.Ordinal) != -1);
            bool deleteEnabled = (property.Description.IndexOf("__MIDELETE__", StringComparison.Ordinal) != -1);

            if (readOnly)
            {
                addEnabled = false;
                editEnabled = false;
                deleteEnabled = false;
            }

            var divOuterControl = GetMIDivOuterControl(property);
            var panelTemplateControl = new PanelTemplateControl
            {
                TemplateTitle = property.Caption + ((property.Description.IndexOf("__OFFICE_USE__", System.StringComparison.Ordinal) != -1) ? " (Office Use Only)" : string.Empty),
                Collapsible = false,
                Width = Unit.Percentage(98),
                ID = "Asi__Wfz__MI__" + property.Name,
                ShowHeader = false
            };

            if (!string.IsNullOrEmpty(property.CssClass))
            {
                panelTemplateControl.EnableTheming = false;
                panelTemplateControl.CssClass = property.CssClass;
            }

            if (property.Description.IndexOf("__SHOW_BORDER__", StringComparison.Ordinal) != -1)
            {
                panelTemplateControl.BorderWidth = 0;
            }

            string miBOName = Utils.Mid(property.Description, "__$$", "$$__");

            if (string.IsNullOrEmpty(miBOName))
                miBOName = GetFormattedFormName(_businessItem.Table.TableName, property.Caption);

            var controllerMultiInstance = BusinessController.NewBusinessController(miBOName);
            var filter = new BusinessFilter[1];
            var webFormZSubmissionKey = new Guid(_businessItem["WebFormZSubmissionKey"].ToString());
            filter[0] = new BusinessFilter("WebFormZSubmissionKey", ComparisonType.Equal, webFormZSubmissionKey);
            controllerMultiInstance.SelectWithFilter(filter, true);
            int miMinRows, miMaxRows;
            Int32.TryParse(property.RangeStart, out miMinRows);
            Int32.TryParse(property.RangeEnd, out miMaxRows);

            if (miMinRows > 0)
            {
                var label2 = new Label
                {
                    ID = panelTemplateControl.ID + "_TextLabel2"
                };
                Label child = label2;
                panelTemplateControl.AddControl(child);
                child.Text = string.Format(("Note: You must add at least {0} {1}"), miMinRows, property.Caption);
                child.CssClass = "Info Required";
            }

            var dcolumns = new DataColumn[controllerMultiInstance.Columns.Count];
            controllerMultiInstance.Columns.CopyTo(dcolumns, 0);
            Array.Sort(dcolumns, new FormBuilderComparer());

            var grid = new RadGrid
            {
                ID = "RadGrid" + property.Name,
                AutoGenerateColumns = false,
                ShowFooter = true,
                Width = Unit.Percentage(100),
                AllowMultiRowEdit = true
            };

            grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Top;
            
            grid.MasterTableView.ID = miBOName + "___" + property.Name;
            if (!addEnabled)
                grid.MasterTableView.ID = grid.MasterTableView.ID + "__NOADDBTN__";

            //if (miMaxRows != 0 && miMaxRows <= controllerMultiInstance.Rows.Count)
            //{
            //    grid.MasterTableView.ID = (grid.MasterTableView.ID.IndexOf("__NOADDBTN__", System.StringComparison.Ordinal) == -1) ? grid.MasterTableView.ID + "__NOADDBTN__" : grid.MasterTableView.ID;
            //}

            grid.MasterTableView.EditMode = GridEditMode.InPlace;
            grid.MasterTableView.CommandItemSettings.ShowRefreshButton = false;
            grid.MasterTableView.Caption = property.Caption;
            grid.BorderWidth = Unit.Pixel(1);
            grid.EnableViewState = true;
            grid.MasterTableView.DataKeyNames = new string[] { "FormMultiInstanceItemKey" };

            grid.ValidationSettings.EnableValidation = true;
            grid.ValidationSettings.ValidationGroup = "RadGridValidationGroup";

            //var newCol;
            foreach (var col in dcolumns)
            {
                if (!col.ColumnName.Equals("CreatedOn") && !col.ColumnName.Equals("UpdatedOn") && !col.ColumnName.Equals("BOCKey") && !col.ColumnName.Equals("UpdatedByUserKey") && !col.ColumnName.Equals("CreatedByUserKey"))
                {
                    var bProperty = col as BusinessProperty;
                    var showTotal = (bProperty.Description.IndexOf("__SHOW_TOTAL__", StringComparison.Ordinal) != -1);
                    var footerPrompt = Asi.Business.WebFormZ.Utils.Mid(bProperty.Description, "__#FP#", "#FP#__");
                    int minTotal = 0, maxTotal = 0;
                    Int32.TryParse(Asi.Business.WebFormZ.Utils.Mid(bProperty.Description, "__#MINTOTAL#", "#MINTOTAL#__"), out minTotal);
                    Int32.TryParse(Asi.Business.WebFormZ.Utils.Mid(bProperty.Description, "__#MAXTOTAL#", "#MAXTOTAL#__"), out maxTotal);
                    if (bProperty.ValueList != null || !bProperty.ValueListQuery.Equals(Guid.Empty))
                    {
                        if (bProperty.HIControlType == AtomHIControlType.DropDownList || bProperty.HIControlType == AtomHIControlType.ComboBox)
                        {
                            var newCol = new GridDropDownColumn
                            {
                                DataField = col.ColumnName,
                                HeaderText = col.Caption,
                                UniqueName = col.ColumnName,
                                FooterText = footerPrompt,
                                ReadOnly = bProperty.IsReadOnly
                            };
                            grid.MasterTableView.Columns.Add(newCol);
                        }
                        else
                        {
                            var newCol = new GridBoundColumn
                            {
                                DataField = col.ColumnName,
                                HeaderText = col.Caption,
                                UniqueName = col.ColumnName,
                                FooterText = footerPrompt,
                                ReadOnly = bProperty.IsReadOnly
                            };
                            grid.MasterTableView.Columns.Add(newCol);
                        }
                    }
                    else if (col.DataType == typeof(string))
                    {
                        var newCol = new GridBoundColumn
                        {
                            DataField = col.ColumnName,
                            HeaderText = col.Caption,
                            UniqueName = col.ColumnName,
                            FooterText = footerPrompt,
                            ReadOnly = bProperty.IsReadOnly
                        };
                        grid.MasterTableView.Columns.Add(newCol);
                    }
                    else if (col.DataType == typeof(DateTime))
                    {
                        var newCol = new GridDateTimeColumn
                        {
                            DataField = col.ColumnName,
                            HeaderText = col.Caption,
                            UniqueName = col.ColumnName,
                            FooterText = footerPrompt,
                            DataFormatString = "{0:d}",
                            ReadOnly = bProperty.IsReadOnly
                        };
                        grid.MasterTableView.Columns.Add(newCol);
                    }
                    else if (col.DataType == typeof(bool))
                    {
                        var newCol = new GridCheckBoxColumn
                        {
                            DataField = col.ColumnName,
                            HeaderText = col.Caption,
                            UniqueName = col.ColumnName,
                            FooterText = footerPrompt,
                            ReadOnly = bProperty.IsReadOnly
                        };
                        grid.MasterTableView.Columns.Add(newCol);
                    }
                    else if (col.DataType == typeof(int) || col.DataType == typeof(float) || col.DataType == typeof(decimal) || col.DataType == typeof(double))
                    {
                        var newCol = new GridNumericColumn
                        {
                            DataField = col.ColumnName,
                            HeaderText = col.Caption,
                            UniqueName = col.ColumnName,
                            FooterText = footerPrompt
                        };
                        if (showTotal) newCol.Aggregate = GridAggregateFunction.Sum;
                        grid.MasterTableView.Columns.Add(newCol);
                        if ( (minTotal > 0) || maxTotal > 0)
                        {
                            var lbl = new Label
                            {
                                Text = string.Format(("Note: {0} aggregate value shouldn't be exceed {1}"), bProperty.Caption, maxTotal)
                            };
                            lbl.Text = (minTotal > 0) ? string.Format(("Note: {0} aggregate value between {1} and {2}"), bProperty.Caption, minTotal, maxTotal) : lbl.Text;
                            lbl.CssClass = "Info Required";
                            panelTemplateControl.AddControl(lbl);
                            var validator = new CustomValidator
                            {
                                ID = bProperty.Name + "_CustomValidator",
                                ValidationGroup = "RadGridValidationGroup",
                                ErrorMessage = lbl.Text
                            };
                            panelTemplateControl.AddControl(validator);
                        }
                    }
                    else if (col.DataType == typeof(Guid))
                    {
                        var newCol = new GridDropDownColumn
                        {
                            DataField = col.ColumnName,
                            HeaderText = col.Caption,
                            UniqueName = col.ColumnName,
                            FooterText = footerPrompt
                        };
                        if (col.ColumnName.Equals("WebFormZSubmissionKey") || col.ColumnName.Equals("FormMultiInstanceItemKey"))
                            newCol.Visible = false;
                        grid.MasterTableView.Columns.Add(newCol);
                    }
                    else
                    {
                        var newCol = new GridBoundColumn
                        {
                            DataField = col.ColumnName,
                            HeaderText = col.Caption,
                            UniqueName = col.ColumnName,
                            FooterText = footerPrompt
                        };
                        grid.MasterTableView.Columns.Add(newCol);
                    }
                }
            }

            var editColumn = new GridEditCommandColumn
            {
                ButtonType = GridButtonColumnType.ImageButton,
                UniqueName = "MIEdit",
                CancelText = "Cancel",
                InsertText = "OK"
            };

            var deleteColumn = new GridButtonColumn
            {
                ConfirmText = "Are you wish to delete this item?",
                CommandName = RadGrid.DeleteCommandName,
                Text = "Delete",
                UniqueName = "DeleteColumn"
            };

            if (editEnabled)
            {
                grid.Columns.Add(editColumn);
            }
            else
            {
                grid.MasterTableView.ID += "__NOEDIT__";
                //if (addEnabled && (grid.MasterTableView.ID.IndexOf("__NOADDBTN__", StringComparison.Ordinal) == -1))
                //    grid.Columns.Add(editColumn);
            }
            if (deleteEnabled)
                grid.Columns.Add(deleteColumn);

            grid.PreRender += GridPreRender;
            grid.ItemCommand += GridItemCommand;
            grid.ItemCreated += GridItemCreated;
            grid.ItemDataBound += GridItemDataBound;
            grid.NeedDataSource += GridNeedDataSource;
            grid.MasterTableView.EnableViewState = true;
            grid.AllowAutomaticInserts = false;
            grid.AllowAutomaticUpdates = false;

            panelTemplateControl.AddControl(grid);
            divOuterControl.Controls.Add(panelTemplateControl);
            return divOuterControl;
        }
 
        void GridPreRender(object sender, EventArgs e)
        {
            DataColumn[] dcolumns = null;
            if ( (((RadGrid)sender).MasterTableView.ID.IndexOf("__NOADDBTN__", System.StringComparison.Ordinal) != -1) || GetMaxRowReached(sender, GetGridDataSource(sender, new Guid(_businessItem["WebFormZSubmissionKey"].ToString()))))
            {
                foreach (GridDataItem dataItem in ((RadGrid)sender).MasterTableView.Items)
                {
                    //((LinkButton)dataItem["EditCommandColumnUniqueName"].Controls[0]).Enabled = false; //ToDisable the Edit button
                    var cmdItem = (GridCommandItem)((RadGrid)sender).MasterTableView.GetItems(GridItemType.CommandItem)[0];
                    ((LinkButton)cmdItem.FindControl("InitInsertButton")).Visible = false;
                    ((Button)cmdItem.FindControl("AddNewRecordButton")).Visible = false;
                }
            }
            foreach (GridColumn col in ((RadGrid)sender).Columns)
            {
                if (col.DataType == typeof(int) || col.DataType == typeof(decimal) || col.DataType == typeof(float) || col.DataType == typeof(double))
                {
                    col.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                    col.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                    col.FooterStyle.HorizontalAlign = HorizontalAlign.Right;
                }
                dcolumns = GetGridColumnProperties(sender);
                foreach (BusinessProperty property in dcolumns)
                    if (!property.ColumnName.Equals("CreatedOn") && !property.ColumnName.Equals("UpdatedOn") && !property.ColumnName.Equals("BOCKey") && !property.ColumnName.Equals("UpdatedByUserKey") && !property.ColumnName.Equals("CreatedByUserKey"))
                        if (property.ColumnName.Equals(col.UniqueName) && property.HIControlWidth != 0)
                            col.HeaderStyle.Width = new Unit(property.HIControlWidth, UnitType.Pixel);
            }

            if (((RadGrid)sender).MasterTableView.ID.IndexOf("__NOEDIT__", StringComparison.Ordinal) == -1)
            {
                //To show the Grid always in EditMode
                foreach (GridItem item in ((RadGrid)sender).MasterTableView.Items)
                {
                    if (item is GridEditableItem)
                    {
                        GridEditableItem editableItem = item as GridDataItem;
                        if (editableItem != null) editableItem.Edit = true;
                    }
                }
                ((RadGrid)sender).Rebind();
            }
        }

        void GridItemCreated(object sender, GridItemEventArgs e)
        {
            if (( (e.Item is GridDataInsertItem) || (e.Item is GridEditableItem) ) && e.Item.IsInEditMode)
            {
                var dcolumns = GetGridColumnProperties(sender);
                var item = e.Item as GridEditableItem;
                foreach (BusinessProperty col in dcolumns)
                {
                    if (!col.ColumnName.Equals("CreatedOn") && !col.ColumnName.Equals("UpdatedOn") && !col.ColumnName.Equals("BOCKey") && !col.ColumnName.Equals("UpdatedByUserKey") && !col.ColumnName.Equals("CreatedByUserKey"))
                    {
                        if (col.DataType == typeof(int) || col.DataType == typeof(float) || col.DataType == typeof(decimal) || col.DataType == typeof(double))
                        {
                            var editor = (GridNumericColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                            editor.NumericTextBox.Attributes.Add("style", "text-align:right;");
                        }
                        if (col.HIControlWidth != 0)
                        {
                            if (col.DataType == typeof(int) || col.DataType == typeof(float) || col.DataType == typeof(decimal) || col.DataType == typeof(double))
                            {
                                var editor = (GridNumericColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                editor.NumericTextBox.Width = new Unit(col.HIControlWidth, UnitType.Pixel);
                            }
                            else if (col.DataType == typeof(DateTime))
                            {
                                var editor = (GridDateTimeColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                editor.PickerControl.Width = new Unit(col.HIControlWidth, UnitType.Pixel);
                            }
                            else if (col.DataType == typeof(bool))
                            {
                            }
                            else if (col.DataType == typeof(Guid))
                            {
                                var editor = (GridDropDownColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                ((RadComboBox)editor.Controls[0]).Width = new Unit(col.HIControlWidth, UnitType.Pixel);
                            }
                            else
                            {
                                var editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                editor.TextBoxControl.Width = new Unit(col.HIControlWidth, UnitType.Pixel);
                            }
                        }
                        if (col.Description.IndexOf("__REQ__", System.StringComparison.Ordinal) != -1)
                        {
                            if (col.ValueList != null || !col.ValueListQuery.Equals(Guid.Empty))
                            {
                                if (col.HIControlType == AtomHIControlType.DropDownList || col.HIControlType == AtomHIControlType.ComboBox)
                                {
                                    var editor = (GridDropDownColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                    var cell = (TableCell)editor.ContainerControl;
                                    var validator = new AsiRequiredFieldValidator
                                    {
                                        ControlToValidate = ((RadComboBox)editor.Controls[0]).ID,
                                        ErrorMessage = "Required",
                                        ValidationGroup = "RadGridValidationGroup"
                                    };
                                    cell.Controls.Add(validator);
                                }
                                else
                                {
                                    var editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                    var cell = (TableCell)editor.ContainerControl;
                                    editor.TextBoxControl.ID = col.ColumnName + "_ID";
                                    var validator = new AsiRequiredFieldValidator
                                    {
                                        ControlToValidate = editor.TextBoxControl.ID,
                                        ErrorMessage = "Required",
                                        ValidationGroup = "RadGridValidationGroup"
                                    };
                                    cell.Controls.Add(validator);
                                }
                            }
                            if (col.DataType == typeof(string))
                            {
                                var editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                var cell = (TableCell)editor.ContainerControl;
                                editor.TextBoxControl.ID = col.ColumnName + "_ID";
                                var validator = new AsiRequiredFieldValidator
                                {
                                    ControlToValidate = editor.TextBoxControl.ID,
                                    ErrorMessage = "Required",
                                    ValidationGroup = "RadGridValidationGroup"
                                };
                                cell.Controls.Add(validator);
                            }
                            else if (col.DataType == typeof(DateTime))
                            {
                                var editor = (GridDateTimeColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                var cell = (TableCell)editor.ContainerControl;
                                var validator = new AsiRequiredFieldValidator
                                {
                                    ControlToValidate = editor.PickerControl.ID,
                                    ErrorMessage = "Required",
                                    ValidationGroup = "RadGridValidationGroup"
                                };
                                cell.Controls.Add(validator);
                            }
                            else if (col.DataType == typeof(bool))
                            {
                                var editor = (GridBoolColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                var cell = (TableCell)editor.ContainerControl;
                                var validator = new CheckBoxValidator
                                {
                                    ControlToValidate = ((CheckBox)editor.Controls[0]).ID,
                                    ErrorMessage = "Required",
                                    ValidationGroup = "RadGridValidationGroup"
                                };
                                cell.Controls.Add(validator);
                            }
                            else if (col.DataType == typeof(int) || col.DataType == typeof(float) || col.DataType == typeof(decimal) || col.DataType == typeof(double))
                            {
                                var editor = (GridNumericColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                var cell = (TableCell)editor.ContainerControl;
                                editor.NumericTextBox.ID = col.ColumnName + "_ID";
                                var validator = new AsiRequiredFieldValidator
                                {
                                    ControlToValidate = editor.NumericTextBox.ID,
                                    ErrorMessage = "Required",
                                    ValidationGroup="RadGridValidationGroup"
                                };
                                cell.Controls.Add(validator);
                            }
                            else if (col.DataType == typeof(Guid))
                            {
                                var editor = (GridDropDownColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                var cell = (TableCell)editor.ContainerControl;
                                var validator = new AsiRequiredFieldValidator
                                {
                                    ControlToValidate = ((RadComboBox)editor.Controls[0]).ID,
                                    ErrorMessage = "Required",
                                    ValidationGroup = "RadGridValidationGroup"
                                };
                                cell.Controls.Add(validator);
                            }
                            else
                            {
                                var editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor(col.ColumnName);
                                var cell = (TableCell)editor.ContainerControl;
                                editor.TextBoxControl.ID = col.ColumnName + "_ID";
                                var validator = new AsiRequiredFieldValidator
                                {
                                    ControlToValidate = editor.TextBoxControl.ID,
                                    ErrorMessage = "Required",
                                    ValidationGroup = "RadGridValidationGroup"
                                };
                                cell.Controls.Add(validator);
                            }
                        }
                    }
                }
                if (e.Item.OwnerTableView.GetColumnSafe("MIEdit") != null)
                {
                    var gridId = ((RadGrid)sender).MasterTableView.ID;
                    if ((gridId.IndexOf("__NOADDBTN__", System.StringComparison.Ordinal) == -1) && (gridId.IndexOf("__NOEDIT__", StringComparison.Ordinal) != -1))
                    {
                        if (e.Item is GridDataInsertItem)
                            item["MIEdit"].Visible = true;
                        else
                            item["MIEdit"].Visible = false;
                    }
                    else
                    {
                        if (!(e.Item is GridDataInsertItem))
                        {
                            //item["MIEdit"].Controls[2].Visible = false; // Cancel Button
                            item["MIEdit"].Controls[1].Visible = true; // Space &nbsp;
                            item["MIEdit"].FindControl("CancelButton").Visible = true;
                        }
                    }
                }

                if (!(e.Item is GridDataInsertItem) && item.OwnerTableView.GetColumnSafe("DeleteColumn") != null)
                    item["DeleteColumn"].Controls[0].Visible = true;
            }
            if (!(e.Item is GridDataInsertItem))
            {
                if (e.Item.OwnerTableView.GetColumnSafe("MIEdit") != null)
                {
                    var gridId = ((RadGrid)sender).MasterTableView.ID;
                    if ((gridId.IndexOf("__NOADDBTN__", System.StringComparison.Ordinal) == -1) && (gridId.IndexOf("__NOEDIT__", StringComparison.Ordinal) != -1))
                    {
                        if ((e.Item is GridEditableItem) && (e.Item as GridEditableItem).OwnerTableView.GetColumnSafe("MIEdit") != null)
                        {
                            (e.Item as GridEditableItem)["MIEdit"].Visible = false;
                        }
                    }
                }
            }
        }

        void GridItemDataBound(object sender, GridItemEventArgs e)
        {
            DataColumn[] dcolumns = null;

            if ((((RadGrid)sender).MasterTableView.ID.IndexOf("__NOADDBTN__", System.StringComparison.Ordinal) != -1) || GetMaxRowReached(sender, GetGridDataSource(sender, new Guid(_businessItem["WebFormZSubmissionKey"].ToString()))))
            {
                if (e.Item is GridCommandItem)
                {
                    Button addButton = e.Item.FindControl("AddNewRecordButton") as Button;
                    addButton.Visible = false;
                    LinkButton lnkButton = (LinkButton)e.Item.FindControl("InitInsertButton");
                    lnkButton.Visible = false;
                }
            }

            if (e.Item is GridEditableItem && e.Item.IsInEditMode) //fire for both edit and insert        
            {
                if(dcolumns == null)
                    dcolumns = GetGridColumnProperties(sender);
                foreach (BusinessProperty col in dcolumns)
                {
                    if (!col.ColumnName.Equals("CreatedOn") && !col.ColumnName.Equals("UpdatedOn") && !col.ColumnName.Equals("BOCKey") && !col.ColumnName.Equals("UpdatedByUserKey") && !col.ColumnName.Equals("CreatedByUserKey"))
                    {
                        if (col.ValueList != null || !col.ValueListQuery.Equals(Guid.Empty))
                        {
                            if (col.HIControlType == AtomHIControlType.DropDownList || col.HIControlType == AtomHIControlType.ComboBox)
                            {
                                var editItem = e.Item as GridEditableItem;
                                GridEditManager editMgr = editItem.EditManager;
                                var ddlEditor = editMgr.GetColumnEditor(col.ColumnName) as GridDropDownListColumnEditor;
                                string selectedValue = DataBinder.Eval(editItem.DataItem, col.ColumnName).ToString();
                                DataTable dt = PopulateDropDown(col);
                                if (ddlEditor != null)
                                {
                                    ddlEditor.DataSource = dt;
                                    ddlEditor.DataValueField = string.IsNullOrEmpty(col.ValueListQueryPersistColumn) ? "Key" : col.ValueListQueryPersistColumn;
                                    ddlEditor.DataTextField = string.IsNullOrEmpty(col.ValueListQueryDisplayColumn) ? "Value" : col.ValueListQueryPersistColumn;
                                    ddlEditor.DataBind();
                                    ddlEditor.SelectedValue = selectedValue;
                                }
                            }
                        }
                    }
                }
            }
            else if (e.Item is GridFooterItem)
            {
                if (dcolumns == null)
                    dcolumns = GetGridColumnProperties(sender);
                var controller = GetGridDataSource(sender, new Guid(_businessItem["WebFormZSubmissionKey"].ToString()));
                            
                foreach (BusinessProperty col in dcolumns)
                {
                    if (!col.ColumnName.Equals("CreatedOn") && !col.ColumnName.Equals("UpdatedOn") && !col.ColumnName.Equals("BOCKey") && !col.ColumnName.Equals("UpdatedByUserKey") && !col.ColumnName.Equals("CreatedByUserKey"))
                    {
                        if (col.HIControlType == AtomHIControlType.Number && (col.Description.IndexOf("__SHOW_TOTAL__", StringComparison.Ordinal) != -1))
                        {
                            var total = controller.Compute("Sum(" + col.ColumnName + ")", string.Empty);
                            var footerText = Asi.Business.WebFormZ.Utils.Mid(col.Description, "__#FP#", "#FP#__");
                            footerText = (string.IsNullOrEmpty(footerText)) ? string.Empty : footerText + ": ";
                            footerText += ((total == DBNull.Value) ? "0" : total.ToString());
                            foreach (GridDataItem dataItem in ((RadGrid)sender).MasterTableView.Items)
                            {
                                var footerItems = ((RadGrid)sender).MasterTableView.GetItems(GridItemType.Footer)[0] as GridFooterItem;
                                if (footerItems != null)
                                    footerItems[col.ColumnName].Text = footerText;
                                if (!string.IsNullOrEmpty(col.RangeEnd))
                                    footerItems[col.ColumnName].Text = footerText + "/" + col.RangeEnd;
                            }
                        }
                    }
                }
            }
        }

        private DataTable PopulateDropDown(BusinessProperty col)
        {
            var ds = new DataSet();
            if (col.ValueList != null)
            {
                ds.Tables.Add();
                ds.Tables[0].Columns.Add(new DataColumn("Key"));
                ds.Tables[0].Columns.Add(new DataColumn("Value"));
                foreach (var pair in col.ValueList)
                {
                    DataRow dr = ds.Tables[0].NewRow();
                    dr["Key"] = pair.Second;
                    dr["Value"] = pair.First;
                    ds.Tables[0].Rows.Add(dr);
                    ds.Tables[0].AcceptChanges();
                }
            }
            else if(!col.ValueListQuery.Equals(Guid.Empty))
            {
                var myQuery = QueryBuilder.Query.NewQuery(col.ValueListQuery);

                string query = myQuery.SqlCommandText();
                using (var dbServer = new Asi.Data.DataServer())
                {
                    ds = dbServer.ExecuteDataSet(System.Data.CommandType.Text, query);
                }
            }
            return ds.Tables[0];
        }

        private static DataColumn[] GetGridColumnProperties(object sender)
        {
            var miBOName = ((RadGrid)sender).MasterTableView.ID.Split(new string[] { "__" }, StringSplitOptions.RemoveEmptyEntries)[0];
            var controllerMultiInstance = BusinessController.NewBusinessController(miBOName);
            var dcolumns = new DataColumn[controllerMultiInstance.Columns.Count];
            controllerMultiInstance.Columns.CopyTo(dcolumns, 0);
            Array.Sort(dcolumns, new FormBuilderComparer());
            return dcolumns;
        }

        private static BusinessController GetGridDataSource(object sender, Guid webFormZSubmissionKey)
        {
            var miBOName = ((RadGrid)sender).MasterTableView.ID.Split(new string[] { "__" }, StringSplitOptions.RemoveEmptyEntries)[0];
            var controllerMultiInstance = BusinessController.NewBusinessController(miBOName);
            var filter = new BusinessFilter[1];
            filter[0] = new BusinessFilter("WebFormZSubmissionKey", ComparisonType.Equal, webFormZSubmissionKey);
            controllerMultiInstance.SelectWithFilter(filter, true);
            return controllerMultiInstance;
        }

        void GridNeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            using (Asi.Security.SecurityContext.Impersonate("MANAGER"))
            {
                var miBOName = ((RadGrid)sender).MasterTableView.ID.Split(new string[] { "__" }, StringSplitOptions.RemoveEmptyEntries)[0];
                var controllerMultiInstance = BusinessController.NewBusinessController(miBOName);
                var filter = new BusinessFilter[1];
                var webFormZSubmissionKey = new Guid(_businessItem["WebFormZSubmissionKey"].ToString());
                filter[0] = new BusinessFilter("WebFormZSubmissionKey", ComparisonType.Equal, webFormZSubmissionKey);
                controllerMultiInstance.SelectWithFilter(filter, true);
                ((RadGrid)sender).DataSource = controllerMultiInstance;
            }
        }

        void GridItemCommand(object sender, GridCommandEventArgs e)
        {
            using (Asi.Security.SecurityContext.Impersonate("MANAGER"))
            {
                var miBOName = ((RadGrid)sender).MasterTableView.ID.Split(new string[] { "___" }, StringSplitOptions.RemoveEmptyEntries)[0];
                
                switch (e.CommandName)
                {
                    case RadGrid.PerformInsertCommandName:
                        InsertMIRecord(e, miBOName, sender);
                        break;
                    case RadGrid.UpdateCommandName:
                        UpdateMIRecord(e, miBOName);
                        break;
                    case RadGrid.DeleteCommandName:
                        DeleteMIRecord(e, miBOName, sender);
                        break;
                }
                GridNeedDataSource(sender, null);
                ((RadGrid)sender).EditIndexes.Clear();
                ((RadGrid)sender).Rebind();
                ((RadGrid)sender).MasterTableView.DataBind();
            }
        }

        void InsertMIRecord(GridCommandEventArgs e, string miBOName, object radGrid)
        {
            try
            {
                if (e.Item is GridEditableItem)
                {
                    var gridEditedItem = e.Item as GridEditableItem;
                    GridEditManager editMan = gridEditedItem.EditManager;
                    var weubFormZSubmissionKey = new Guid(_businessItem["WebFormZSubmissionKey"].ToString());
                    var controller = GetGridDataSource(radGrid, weubFormZSubmissionKey);
                    
                    var showTotalColumns = new Dictionary<string, string>();
                    foreach (BusinessProperty col in controller.Columns)
                    {
                        if (!col.ColumnName.Equals("CreatedOn") && !col.ColumnName.Equals("UpdatedOn") && !col.ColumnName.Equals("BOCKey") && !col.ColumnName.Equals("UpdatedByUserKey") && !col.ColumnName.Equals("CreatedByUserKey") && !col.ColumnName.Equals("FormMultiInstanceItemKey") && !col.ColumnName.Equals("WebFormZSubmissionKey"))
                        {
                            var showTotal = (col.Description.IndexOf("__SHOW_TOTAL__", StringComparison.Ordinal) != -1);
                            int minTotal = 0, maxTotal = 0;
                            Int32.TryParse(Asi.Business.WebFormZ.Utils.Mid(col.Description, "__#MINTOTAL#", "#MINTOTAL#__"), out minTotal);
                            Int32.TryParse(Asi.Business.WebFormZ.Utils.Mid(col.Description, "__#MAXTOTAL#", "#MAXTOTAL#__"), out maxTotal);
                            if ((minTotal > 0 || maxTotal > 0)) //&& showTotal)
                                showTotalColumns.Add(col.ColumnName, minTotal.ToString(CultureInfo.InvariantCulture) + "$" + maxTotal.ToString(CultureInfo.InvariantCulture));
                        }
                    }

                    foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
                    {
                        if (showTotalColumns.ContainsKey(column.UniqueName))
                        {
                            var value = showTotalColumns[column.UniqueName].ToString(CultureInfo.InvariantCulture);
                            int minTotal = Convert.ToInt32(value.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries)[0]);
                            int maxTotal = Convert.ToInt32(value.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries)[1]);
                            int aggregateValue = Convert.ToInt32(controller.Compute("SUM(" + column.UniqueName + ")", string.Empty));

                            DataRow[] rows = controller.Select("FormMultiInstanceItemKey = '" + gridEditedItem.OwnerTableView.DataKeyValues[gridEditedItem.ItemIndex]["FormMultiInstanceItemKey"].ToString() + "'");
                            int oldValue = 0;
                            if (rows[0][column.UniqueName] != DBNull.Value)
                                oldValue = Convert.ToInt32(rows[0][column.UniqueName]);

                            string editorText = "0";
                            var editableCol = (column as IGridEditableColumn);
                            if (editableCol != null && editableCol.IsEditable)
                            {
                                IGridColumnEditor editor = editMan.GetColumnEditor(editableCol);
                                if (editor is GridTextColumnEditor)
                                {
                                    editorText = (editor as GridTextColumnEditor).Text;
                                }
                            }
                            int newValue = 0;
                            if (string.IsNullOrEmpty(editorText))
                                newValue = Convert.ToInt32(editorText);

                            int valueToCompare = aggregateValue - oldValue + newValue;

                            if (minTotal < valueToCompare)
                            {
                                bool valid = true;
                                if (maxTotal <= 0)
                                    valid = true;
                                else if (maxTotal < valueToCompare)
                                    valid = true;
                                else
                                    valid = false;
                                var validator = FindChildControl<CustomValidator>(e.Item.Parent.Parent.Parent.Parent.Parent, column.UniqueName + "_CustomValidator");
                                validator.IsValid = valid;
                                if (!valid)
                                    return;
                            }
                        }
                    }

                    var row = controller.NewRow();
                    var newValues = new System.Collections.Hashtable();
                    e.Item.OwnerTableView.ExtractValuesFromItem(newValues, gridEditedItem);
                    row["FormMultiInstanceItemKey"] = Guid.NewGuid();
                    row["WebFormZSubmissionKey"] = weubFormZSubmissionKey;

                    ////
                    foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
                    {
                        if (column is IGridEditableColumn && !column.UniqueName.Equals("WebFormZSubmissionKey") && !column.UniqueName.Equals("FormMultiInstanceItemKey"))
                        {
                            var editableCol = (column as IGridEditableColumn);
                            if (editableCol.IsEditable)
                            {
                                IGridColumnEditor editor = editMan.GetColumnEditor(editableCol);

                                object editorValue = null;

                                if (editor is GridTextColumnEditor)
                                {
                                    editorValue = (editor as GridTextColumnEditor).Text;
                                }

                                if (editor is GridBoolColumnEditor)
                                {
                                    editorValue = (editor as GridBoolColumnEditor).Value;
                                }

                                if (editor is GridDropDownColumnEditor)
                                {
                                    editorValue = (editor as GridDropDownColumnEditor).SelectedValue;
                                }

                                try
                                {
                                    if (column.DataType == typeof(DateTime) && editorValue != null && !string.IsNullOrEmpty(editorValue.ToString()))
                                        row[column.UniqueName] = Convert.ToDateTime(editorValue);
                                    else if (column.DataType == typeof(Guid))
                                    {
                                        if (editorValue != null && !string.IsNullOrEmpty(editorValue.ToString()))
                                            row[column.UniqueName] = new Guid(editorValue.ToString());
                                        else
                                            row[column.UniqueName] = Guid.NewGuid();
                                    }
                                    else
                                    {
                                        if (editorValue != null && !string.IsNullOrEmpty(editorValue.ToString()))
                                            row[column.UniqueName] = editorValue.ToString();
                                        else if (row.Table.Columns[column.UniqueName].AllowDBNull)
                                            row[column.UniqueName] = DBNull.Value;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    e.Canceled = true;
                                }
                            }
                        }
                    }
                    ////
                    controller.Rows.Add(row);
                    controller.Commit();
                }
            }
            catch (Exception ex)
            { }
        }

        void UpdateMIRecord(GridCommandEventArgs e, string miBOName)
        {
            try
            {
                if (e.Item is GridEditableItem)
                {
                    var gridEditedItem = e.Item as GridEditableItem;
                    GridEditManager editMan = gridEditedItem.EditManager;
                    var controller = BusinessController.NewBusinessController(miBOName);
                    var newValues = new System.Collections.Hashtable();
                    e.Item.OwnerTableView.ExtractValuesFromItem(newValues, gridEditedItem);
                    controller.SelectWithFilter(new BusinessFilter[] { new BusinessFilter("WebFormZSubmissionKey", ComparisonType.Equal, _businessItem["WebFormZSubmissionKey"]) }, true);

                    var showTotalColumns = new Dictionary<string, string>();
                    foreach (BusinessProperty col in controller.Columns)
                    {
                        if (!col.ColumnName.Equals("CreatedOn") && !col.ColumnName.Equals("UpdatedOn") && !col.ColumnName.Equals("BOCKey") && !col.ColumnName.Equals("UpdatedByUserKey") && !col.ColumnName.Equals("CreatedByUserKey") && !col.ColumnName.Equals("FormMultiInstanceItemKey") && !col.ColumnName.Equals("WebFormZSubmissionKey"))
                        {
                            var showTotal = (col.Description.IndexOf("__SHOW_TOTAL__", StringComparison.Ordinal) != -1);
                            int minTotal = 0, maxTotal = 0;
                            Int32.TryParse(Asi.Business.WebFormZ.Utils.Mid(col.Description, "__#MINTOTAL#", "#MINTOTAL#__"), out minTotal);
                            Int32.TryParse(Asi.Business.WebFormZ.Utils.Mid(col.Description, "__#MAXTOTAL#", "#MAXTOTAL#__"), out maxTotal);
                            if ((minTotal > 0 || maxTotal > 0)) //&& showTotal)
                                showTotalColumns.Add(col.ColumnName, minTotal.ToString(CultureInfo.InvariantCulture) + "$" + maxTotal.ToString(CultureInfo.InvariantCulture));
                        }
                    }

                    foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
                    {
                        if (showTotalColumns.ContainsKey(column.UniqueName))
                        {
                            var value = showTotalColumns[column.UniqueName].ToString(CultureInfo.InvariantCulture);
                            int minTotal = Convert.ToInt32(value.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries)[0]);
                            int maxTotal = Convert.ToInt32(value.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries)[1]);
                            int aggregateValue = Convert.ToInt32(controller.Compute("SUM(" + column.UniqueName + ")", string.Empty));

                            DataRow[] rows = controller.Select("FormMultiInstanceItemKey = '" + gridEditedItem.OwnerTableView.DataKeyValues[gridEditedItem.ItemIndex]["FormMultiInstanceItemKey"].ToString() + "'");
                            int oldValue = 0;
                            if (rows[0][column.UniqueName] != DBNull.Value)
                                oldValue = Convert.ToInt32(rows[0][column.UniqueName]);

                            string editorText = "0";
                            var editableCol = (column as IGridEditableColumn);
                            if (editableCol != null && editableCol.IsEditable)
                            {
                                IGridColumnEditor editor = editMan.GetColumnEditor(editableCol);
                                if (editor is GridTextColumnEditor)
                                {
                                    editorText = (editor as GridTextColumnEditor).Text;
                                }
                            }
                            int newValue = 0;
                            if (string.IsNullOrEmpty(editorText))
                                newValue = Convert.ToInt32(editorText);

                            int valueToCompare = aggregateValue - oldValue + newValue;

                            if (minTotal < valueToCompare)
                            {
                                bool valid = true;
                                if (maxTotal <= 0)
                                    valid = true;
                                else if (maxTotal < valueToCompare)
                                    valid = true;
                                else
                                    valid = false;
                                var validator = FindChildControl<CustomValidator>(e.Item.Parent.Parent.Parent.Parent.Parent, column.UniqueName + "_CustomValidator");
                                validator.IsValid = valid;
                                if (!valid)
                                    return;
                            }
                        }

                        if (column is IGridEditableColumn && !column.UniqueName.Equals("WebFormZSubmissionKey") && !column.UniqueName.Equals("FormMultiInstanceItemKey"))
                        {
                            var editableCol = (column as IGridEditableColumn);
                            if (editableCol.IsEditable)
                            {
                                IGridColumnEditor editor = editMan.GetColumnEditor(editableCol);

                                object editorValue = null;

                                if (editor is GridTextColumnEditor)
                                {
                                    editorValue = (editor as GridTextColumnEditor).Text;
                                }

                                if (editor is GridBoolColumnEditor)
                                {
                                    editorValue = (editor as GridBoolColumnEditor).Value;
                                }

                                if (editor is GridDropDownColumnEditor)
                                {
                                    editorValue = (editor as GridDropDownColumnEditor).SelectedValue;
                                }

                                if (editor is GridDateTimeColumnEditor)
                                {
                                    editorValue = (editor as GridDateTimeColumnEditor).Text;
                                }

                                try
                                {
                                    DataRow[] changedRows = controller.Select("FormMultiInstanceItemKey = '" + gridEditedItem.OwnerTableView.DataKeyValues[gridEditedItem.ItemIndex]["FormMultiInstanceItemKey"].ToString() + "'");
                                    //changedRows[0][column.UniqueName] = editorValue;

                                    if (column.DataType == typeof(DateTime) && editorValue != null && !string.IsNullOrEmpty(editorValue.ToString()))
                                        changedRows[0][column.UniqueName] = Convert.ToDateTime(editorValue);
                                    else if (column.DataType == typeof(Guid))
                                    {
                                        if (editorValue != null && !string.IsNullOrEmpty(editorValue.ToString()))
                                            changedRows[0][column.UniqueName] = new Guid(editorValue.ToString());
                                        else
                                            changedRows[0][column.UniqueName] = Guid.NewGuid();
                                    }
                                    else
                                    {
                                        if (editorValue != null && !string.IsNullOrEmpty(editorValue.ToString()))
                                            changedRows[0][column.UniqueName] = editorValue.ToString();
                                        else if (changedRows[0].Table.Columns[column.UniqueName].AllowDBNull)
                                            changedRows[0][column.UniqueName] = DBNull.Value;
                                    }

                                    controller.Commit();
                                }
                                catch (Exception ex)
                                {
                                    e.Canceled = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
        }

        void DeleteMIRecord(GridCommandEventArgs e, string miBOName, object radGrid)
        {
            try
            {
                var gridDataItem = e.Item as GridDataItem;
                if (gridDataItem != null)
                {
                    Guid formMultiInstanceItemKey = new Guid(gridDataItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FormMultiInstanceItemKey"].ToString());
                    var controller = BusinessController.NewBusinessController(miBOName);
                    controller.SelectWithFilter(new BusinessFilter[] { new BusinessFilter("WebFormZSubmissionKey", ComparisonType.Equal, _businessItem["WebFormZSubmissionKey"]) }, true);

                    if (controller.Rows.Find(formMultiInstanceItemKey) != null)
                    {
                        controller.Rows.Find(formMultiInstanceItemKey).Delete();
                        controller.Commit();
                    }

                }
            }
            catch (Exception ex)
            { }
        }

        private bool GetMaxRowReached(object radGrid, BusinessController controller)
        {

            var businessPropertyName = ((RadGrid)radGrid).ID.Replace("RadGrid", "");
            int maxRows = Convert.ToInt32(_businessItem.BusinessProperty(businessPropertyName).RangeEnd);
            if (maxRows == 0)
                return false;
            return (maxRows <= controller.Rows.Count);
        }

        #endregion

Could any one help to solve this issue.

Thanks in advance
Prakasam
Top achievements
Rank 1
 answered on 25 Jan 2013
1 answer
78 views
Hi,

I have updated my existing application with rad controls- radcombobox, radlistbox etc, everything was working just fine but as soon as we launched our application in production the radcontrols stopped working. We disabled our state server and everything started working again but without state server our customers are facing log out /time out issues
The javascript error on the page is as below.

After looking into the details, looks like some control is affecting the state. Could someone please suggest something if they had faced similar kind of  issue.

Thanks,
Ruby

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Error parsing near' ?'
Telerik.web.UI.WebResource.axd
URI: https://....................../Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=uxSmplu....
Peter Filipov
Telerik team
 answered on 25 Jan 2013
Narrow your results
Selected tags
Tags
+? more
Top users last month
Top achievements
Rank 1
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
ivory
Top achievements
Rank 1
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
YF
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Top achievements
Rank 1
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
ivory
Top achievements
Rank 1
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
YF
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?