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

[Solved] Hierarchical grid insert/update do not fire after IsItemInserted = false and ClearEditItems()

1 Answer 194 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Yoong
Top achievements
Rank 1
Yoong asked on 01 Aug 2013, 05:32 PM
Hello,

I have a hierarchical grid with MasterTableView and DetailTable (see below) with following problems:

  1. When running the example with multiple outstanding Add or Update forms, clicking on either the insert or update link will validate all the forms as shown in the attached MultipleOpenForm.png. Is there a way to prevent the validation of all outstanding forms and only restrict validation to the form where user click insert or update link? I tried to use validation group but could not find a way to link it to the insert or update link. Would greatly appreciate it if you can show me an example of how to do that for the RadGrid
  2. In order to prevent outstanding multiple forms open at the same time, I have added the following code to reset all outstanding edit form as shown below:
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
        {
            //Clear and reset all outstanding edit form
            e.Item.OwnerTableView.IsItemInserted = false;
            e.Item.OwnerTableView.ClearEditItems();
            e.Item.OwnerTableView.ClearChildEditItems();
    Add these codes will close all outstanding forms and will only allow one form open at a given time. Unfortunately, user will no longer able to insert or update an item when clicking on the insert or update link. The form will close without calling the Insert or Update events as well as other events defined in the RadGrid as shown below:
    <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False" OnNeedDataSource="RadGrid1_NeedDataSource"
        OnDetailTableDataBind="RadGrid1_DetailTableDataBind" OnInsertCommand="RadGrid1_InsertCommand"
        OnUpdateCommand="RadGrid1_UpdateCommand" OnDeleteCommand="RadGrid1_DeleteCommand"
        OnEditCommand="RadGrid1_EditCommand" OnItemCreated="RadGrid1_ItemCreated" OnItemDataBound="RadGrid1_ItemDataBound"
        OnItemCommand="RadGrid1_ItemCommand">
    Only the delete event work. I searched the entire forum but did not find a solution to this problem. Can you please help to resolve this problem. It is a show stopper for us.
  3. The Date (Birth Date) RequiredField validation does not work for the DetailTable GridTableView even though it is exactly the same as the Parent Birth Date (see MultipleOpenForm.png). Can you tell me what wrong with the Child Date?
    <DetailTables>
         <telerik:GridTableView DataKeyNames="ID,DependentTobaccoUsage,DependentWellnessFactor"
             Name="Child" CommandItemDisplay="Top" CommandItemSettings-AddNewRecordText="Add new dependent">
             <Columns>
                 <telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID" ReadOnly="true"
                     Visible="false">
                 </telerik:GridBoundColumn>
                 <telerik:GridDateTimeColumn DataField="DependentDOB" HeaderText="Birth Date<span style='color:#CD4800'>*</span>"
                     SortExpression="DependentDOB" UniqueName="DependentDOB" DataFormatString="{0:MM/dd/yyyy}"
                     HeaderStyle-CssClass="bold" ColumnValidationSettings-EnableRequiredFieldValidation="True">
                     <ColumnValidationSettings EnableRequiredFieldValidation="true" RequiredFieldValidator-Display="Dynamic">
                         <RequiredFieldValidator ForeColor="Red" Text="*This field is required">
                         </RequiredFieldValidator>
                     </ColumnValidationSettings>
                 </telerik:GridDateTimeColumn>

Thanks in advance for your help!

Here is the aspx we use.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="TestWebTelerik._Default" %>
 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to ASP.NET!
    </h2>
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
    </telerik:RadScriptManager>
    <telerik:RadAjaxManager runat="server" ID="RadAjaxManager1">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
        <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False" OnNeedDataSource="RadGrid1_NeedDataSource"
            OnDetailTableDataBind="RadGrid1_DetailTableDataBind" OnInsertCommand="RadGrid1_InsertCommand"
            OnUpdateCommand="RadGrid1_UpdateCommand" OnDeleteCommand="RadGrid1_DeleteCommand"
            OnEditCommand="RadGrid1_EditCommand" OnItemCreated="RadGrid1_ItemCreated" OnItemDataBound="RadGrid1_ItemDataBound"
            OnItemCommand="RadGrid1_ItemCommand">
            <MasterTableView DataKeyNames="ID,TobaccoUsage,WellnessFactor,MedicalClass,DentalClass"
                Name="Parent" CommandItemDisplay="Top" CommandItemSettings-AddNewRecordText="Add new subscriber"
                ExpandCollapseColumn-ButtonType="LinkButton">
                <Columns>
                    <telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID" ReadOnly="true"
                        Visible="false">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="MedicalClass" UniqueName="MedicalClass" HeaderText="MedicalClass"
                        ReadOnly="true" Visible="false">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="DentalClass" UniqueName="DentalClass" HeaderText="DentalClass"
                        ReadOnly="true" Visible="false">
                    </telerik:GridBoundColumn>
                    <telerik:GridDateTimeColumn DataField="DOB" HeaderText="Birth Date<span style='color:#CD4800'>*</span>"
                        SortExpression="DOB" UniqueName="DOB" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="bold"
                        ColumnValidationSettings-EnableRequiredFieldValidation="True">
                        <ColumnValidationSettings EnableRequiredFieldValidation="true" RequiredFieldValidator-Display="Dynamic">
                            <RequiredFieldValidator ForeColor="Red" Text="*This field is required">
                            </RequiredFieldValidator>
                        </ColumnValidationSettings>
                    </telerik:GridDateTimeColumn>
                    <telerik:GridBoundColumn DataField="ZipCode" UniqueName="ZipCode" HeaderText="Zip Code<span style='color:#CD4800'>*</span>"
                        DataFormatString="{0:#####-0000}">
                        <ColumnValidationSettings EnableRequiredFieldValidation="true" RequiredFieldValidator-CssClass="inline"
                            RequiredFieldValidator-Display="Dynamic">
                            <RequiredFieldValidator ForeColor="Red" Text="*This field is required">
                            </RequiredFieldValidator>
                        </ColumnValidationSettings>
                    </telerik:GridBoundColumn>
                    <telerik:GridTemplateColumn HeaderText="Tobacco Usage<span style='color:#CD4800'>*</span>">
                        <ItemTemplate>
                            <%#DataBinder.Eval(Container.DataItem, "TobaccoUsage")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <telerik:RadComboBox Height="100px" Width="150px" Skin="WebBlue" ID="TobaccoUsageComboBox"
                                DataTextField="TobaccoUsage" DataValueField="TobaccoUsage" EmptyMessage="Please Select..."
                                runat="server" EnableVirtualScrolling="true" MarkFirstMatch="true" AllowCustomText="true"
                                CausesValidation="false" AutoPostBack="false" NoWrap="True">
                                <Items>
                                    <telerik:RadComboBoxItem Text="Yes" Value="Yes"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="No" Value="No"></telerik:RadComboBoxItem>
                                </Items>
                            </telerik:RadComboBox>
                            <asp:RequiredFieldValidator ID="ValidateTobaccoUsageComboBox" runat="server" ControlToValidate="TobaccoUsageComboBox"
                                ErrorMessage="*This field is required" InitialValue="" ForeColor="Red">
                            </asp:RequiredFieldValidator>
                        </EditItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridTemplateColumn HeaderText="Wellness Factor<span style='color:#CD4800'>*</span>">
                        <ItemTemplate>
                            <%#DataBinder.Eval(Container.DataItem, "WellnessFactor")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <telerik:RadComboBox Height="100px" Width="150px" Skin="WebBlue" ID="WellnessFactorComboBox"
                                DataTextField="WellnessFactor" DataValueField="WellnessFactor" EmptyMessage="Please Select..."
                                runat="server" EnableVirtualScrolling="true" MarkFirstMatch="true" AllowCustomText="true"
                                CausesValidation="false" AutoPostBack="false" NoWrap="True">
                                <Items>
                                    <telerik:RadComboBoxItem Text="Excellent" Value="Excellent"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="VeryGood" Value="VeryGood"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Good" Value="Good"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Fair" Value="Fair"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Poor" Value="Poor"></telerik:RadComboBoxItem>
                                </Items>
                            </telerik:RadComboBox>
                            <asp:RequiredFieldValidator ID="ValidateWellnessFactorComboBox" runat="server" ControlToValidate="WellnessFactorComboBox"
                                ErrorMessage="*This field is required" InitialValue="" ForeColor="Red">
                            </asp:RequiredFieldValidator>
                        </EditItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridTemplateColumn HeaderText="Medical Class<span style='color:#CD4800'>*</span>">
                        <ItemTemplate>
                            <%#DataBinder.Eval(Container.DataItem, "MedicalClassDisplay")%>
                            <%--Medical Class--%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <telerik:RadComboBox Height="100px" Width="150px" Skin="WebBlue" ID="MedicalClassComboBox"
                                DataTextField="MedicalClassDisplay" DataValueField="MedicalClass" EmptyMessage="Please Select..."
                                runat="server" EnableVirtualScrolling="true" MarkFirstMatch="true" AllowCustomText="true"
                                CausesValidation="false" AutoPostBack="false" NoWrap="True">
                                <Items>
                                    <telerik:RadComboBoxItem Text="None" Value="None"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Individual Only" Value="INDIV"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Employee and Spouse" Value="INDIVS"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Employee and 1 Child" Value="INDIV1"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Employee and Children" Value="INDIVC"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Full Family" Value="FAMILY"></telerik:RadComboBoxItem>
                                </Items>
                            </telerik:RadComboBox>
                            <asp:RequiredFieldValidator ID="ValidateMedicalClassComboBox" runat="server" ControlToValidate="MedicalClassComboBox"
                                ErrorMessage="*This field is required" InitialValue="" ForeColor="Red">
                            </asp:RequiredFieldValidator>
                        </EditItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridTemplateColumn HeaderText="Dental Class<span style='color:#CD4800'>*</span>">
                        <ItemTemplate>
                            <%#DataBinder.Eval(Container.DataItem, "DentalClassDisplay")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <telerik:RadComboBox Height="100px" Width="150px" Skin="WebBlue" ID="DentalClassComboBox"
                                DataTextField="DentalClassDisplay" DataValueField="DentalClass" EmptyMessage="Please Select..."
                                runat="server" EnableVirtualScrolling="true" MarkFirstMatch="true" AllowCustomText="true"
                                CausesValidation="false" AutoPostBack="false" NoWrap="True">
                                <Items>
                                    <telerik:RadComboBoxItem Text="None" Value="None"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Individual Only" Value="INDIV"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Employee and Spouse" Value="INDIVS"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Employee and 1 Child" Value="INDIV1"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Employee and Children" Value="INDIVC"></telerik:RadComboBoxItem>
                                    <telerik:RadComboBoxItem Text="Full Family" Value="FAMILY"></telerik:RadComboBoxItem>
                                </Items>
                            </telerik:RadComboBox>
                            <asp:RequiredFieldValidator ID="ValidateDentalClassComboBox" runat="server" ControlToValidate="DentalClassComboBox"
                                ErrorMessage="*This field is required" InitialValue="" ForeColor="Red">
                            </asp:RequiredFieldValidator>
                        </EditItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridEditCommandColumn>
                    </telerik:GridEditCommandColumn>
                    <telerik:GridButtonColumn CommandName="Delete" Text="Delete" ConfirmText="Delete record?">
                    </telerik:GridButtonColumn>
                </Columns>
                <DetailTables>
                    <telerik:GridTableView DataKeyNames="ID,DependentTobaccoUsage,DependentWellnessFactor"
                        Name="Child" CommandItemDisplay="Top" CommandItemSettings-AddNewRecordText="Add new dependent">
                        <Columns>
                            <telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID" ReadOnly="true"
                                Visible="false">
                            </telerik:GridBoundColumn>
                            <telerik:GridDateTimeColumn DataField="DependentDOB" HeaderText="Birth Date<span style='color:#CD4800'>*</span>"
                                SortExpression="DependentDOB" UniqueName="DependentDOB" DataFormatString="{0:MM/dd/yyyy}"
                                HeaderStyle-CssClass="bold" ColumnValidationSettings-EnableRequiredFieldValidation="True">
                                <ColumnValidationSettings EnableRequiredFieldValidation="true" RequiredFieldValidator-Display="Dynamic">
                                    <RequiredFieldValidator ForeColor="Red" Text="*This field is required">
                                    </RequiredFieldValidator>
                                </ColumnValidationSettings>
                            </telerik:GridDateTimeColumn>
                            <telerik:GridTemplateColumn HeaderText="Tobacco Usage<span style='color:#CD4800'>*</span>">
                                <ItemTemplate>
                                    <%#DataBinder.Eval(Container.DataItem, "DependentTobaccoUsage")%>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <telerik:RadComboBox Height="100px" Width="150px" Skin="WebBlue" ID="DependentTobaccoUsageComboBox"
                                        DataTextField="DependentTobaccoUsage" DataValueField="DependentTobaccoUsage"
                                        EmptyMessage="Please Select..." runat="server" EnableVirtualScrolling="true"
                                        MarkFirstMatch="true" AllowCustomText="true" CausesValidation="false" AutoPostBack="false"
                                        NoWrap="True">
                                        <Items>
                                            <telerik:RadComboBoxItem Text="Yes" Value="Yes"></telerik:RadComboBoxItem>
                                            <telerik:RadComboBoxItem Text="No" Value="No"></telerik:RadComboBoxItem>
                                        </Items>
                                    </telerik:RadComboBox>
                                    <asp:RequiredFieldValidator ID="ValidateDependentTobaccoUsageComboBox" runat="server"
                                        ControlToValidate="DependentTobaccoUsageComboBox" ErrorMessage="*This field is required"
                                        InitialValue="" ForeColor="Red">
                                    </asp:RequiredFieldValidator>
                                </EditItemTemplate>
                            </telerik:GridTemplateColumn>
                            <telerik:GridTemplateColumn HeaderText="Wellness Factor<span style='color:#CD4800'>*</span>">
                                <ItemTemplate>
                                    <%#DataBinder.Eval(Container.DataItem, "DependentWellnessFactor")%>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <telerik:RadComboBox Height="100px" Width="150px" Skin="WebBlue" ID="DependentWellnessFactorComboBox"
                                        DataTextField="DependentWellnessFactor" DataValueField="DependentWellnessFactor"
                                        EmptyMessage="Please Select..." runat="server" EnableVirtualScrolling="true"
                                        MarkFirstMatch="true" AllowCustomText="true" CausesValidation="false" AutoPostBack="false"
                                        NoWrap="True">
                                        <Items>
                                            <telerik:RadComboBoxItem Text="Excellent" Value="Excellent"></telerik:RadComboBoxItem>
                                            <telerik:RadComboBoxItem Text="VeryGood" Value="VeryGood"></telerik:RadComboBoxItem>
                                            <telerik:RadComboBoxItem Text="Good" Value="Good"></telerik:RadComboBoxItem>
                                            <telerik:RadComboBoxItem Text="Fair" Value="Fair"></telerik:RadComboBoxItem>
                                            <telerik:RadComboBoxItem Text="Poor" Value="Poor"></telerik:RadComboBoxItem>
                                        </Items>
                                    </telerik:RadComboBox>
                                    <asp:RequiredFieldValidator ID="ValidateDependentWellnessFactorComboBox" runat="server"
                                        ControlToValidate="DependentWellnessFactorComboBox" ErrorMessage="*This field is required"
                                        InitialValue="" ForeColor="Red">
                                    </asp:RequiredFieldValidator>
                                </EditItemTemplate>
                            </telerik:GridTemplateColumn>
                            <telerik:GridEditCommandColumn>
                            </telerik:GridEditCommandColumn>
                            <telerik:GridButtonColumn CommandName="Delete" Text="Delete" ConfirmText="Delete record?">
                            </telerik:GridButtonColumn>
                        </Columns>
                    </telerik:GridTableView>
                </DetailTables>
            </MasterTableView>
        </telerik:RadGrid>
    </telerik:RadAjaxPanel>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">
            www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&;clcid=0x409"
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>
</asp:Content>

Here is the code behind file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
 
namespace TestWebTelerik
{
    [Serializable]
    public class Child
    {
        public int ID {get; set;}
        public DateTime DependentDOB { get; set; }
        public string DependentTobaccoUsage { get; set; }
        public string DependentWellnessFactor { get; set; }
        public Child(int id, DateTime dob, string tobaccoUsage, string wellnessFactor)
        {
            ID = id;
            DependentDOB = dob;
            DependentTobaccoUsage = tobaccoUsage;
            DependentWellnessFactor = wellnessFactor;
        }
    }
 
    [Serializable]
    public class ParentChild
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public DateTime DOB { get; set; }
        public string ZipCode { get; set; }
        public string TobaccoUsage { get; set; }
        public string WellnessFactor { get; set; }
        public string MedicalClass { get; set; }
        public string MedicalClassDisplay { get; set; }
        public string DentalClass { get; set; }
        public string DentalClassDisplay { get; set; }
        public List<Child> listChild { get; set; }
        public ParentChild(int id, string name, DateTime dob, string zipCode,
            string tobaccoUsage, string wellnessFactor,
            string medicalClass, string medicalClassDisplay,
            string dentalClass, string dentalClassDisplay)
        {
            ID = id;
            Name = name;
            DOB = dob;
            ZipCode = zipCode;
            TobaccoUsage = tobaccoUsage;
            WellnessFactor = wellnessFactor;
            MedicalClass = medicalClass;
            MedicalClassDisplay = medicalClassDisplay;
            DentalClass = dentalClass;
            DentalClassDisplay = dentalClassDisplay;
            listChild = new List<Child>();
        }
    }
     
    public partial class _Default : System.Web.UI.Page
    {
        List<ParentChild> listParentChild = new List<ParentChild>();
        Dictionary<string, string> medicalDentalClass = new Dictionary<string, string>()
        {
           {"None","None"},
           {"INDIV","Individual Only"},
           {"INDIVS","Employee and Spouse"},
           {"INDIV1","Employee and 1 Child"},
           {"INDIVC","Employee and Children"},
           {"FAMILY","Full Family"},
        };
 
        private void CreateSampleData()
        {
            for (int i = 1; i <= 3; i++)
            {
                ParentChild parentChild = new ParentChild(i, "ParentName" + i, DateTime.Now, "02421", "No","Excellent","INDIV", "Individual Only", "INDIV", "Individual Only");
                for (int j = 1; j <= 2; j++)
                {
                    Child child = new Child(j, DateTime.Now, "No","VeryGood");
                    parentChild.listChild.Add(child);
                }
                listParentChild.Add(parentChild);
                //listParentChild.Add(i.ToString(), parentChild);
            }
        }
 
        private int CreateNewParentId()
        {
            if (listParentChild.Count == 0)
                return 1;
            else
            {
                var maxQuery = (from pc in listParentChild
                                 select pc.ID).Max();
                return maxQuery + 1;
                //return listParentChild[listParentChild.Count - 1].ID + 1;
            }
        }
 
        private int CreateNewChildId(int parentId)
        {
            ParentChild parentChild = listParentChild.Where(item => item.ID == parentId).Single();
            if (parentChild.listChild.Count == 0)
                return 1;
            else
            {
                var maxQuery = (from c in parentChild.listChild
                                select c.ID).Max();
                return maxQuery + 1;
                //return parentChild.listChild[parentChild.listChild.Count - 1].ID + 1;
            }
        }
 
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CreateSampleData();
                ViewState["listParentChild"] = listParentChild;
            }
            else
            {
                listParentChild = (List<ParentChild>)ViewState["listParentChild"];
            }
        }
 
        protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var query = from item in listParentChild
                        select new { ID = item.ID,
                                     DOB = item.DOB,
                                     ZipCode = item.ZipCode,
                                     TobaccoUsage = item.TobaccoUsage,
                                     WellnessFactor = item.WellnessFactor,
                                     MedicalClass = item.MedicalClass,
                                     MedicalClassDisplay = item.MedicalClassDisplay,
                                     DentalClass = item.DentalClass,
                                     DentalClassDisplay = item.DentalClassDisplay,
                                     Name = item.Name
                        };
 
            RadGrid1.DataSource = query.ToArray();
        }
 
        protected void RadGrid1_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
        {
            GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
 
            string parentID = e.DetailTableView.ParentItem.GetDataKeyValue("ID").ToString();
 
            ParentChild parentChild = listParentChild.Where(item => item.ID == Convert.ToInt32(parentID)).Single();
            var query = from item in parentChild.listChild
                        select new { ID = item.ID,
                                        DependentDOB = item.DependentDOB,
                                        DependentTobaccoUsage = item.DependentTobaccoUsage,
                                        DependentWellnessFactor = item.DependentWellnessFactor
                                    };
 
            e.DetailTableView.DataSource = query.ToArray();
        }
 
        protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            
            if (e.Item.OwnerTableView.Name == "Parent")
            {
 
                int id = CreateNewParentId();
                RadDatePicker picker = (item["DOB"].Controls[0] as RadDatePicker);
                string DOB = picker.SelectedDate != null ? picker.SelectedDate.Value.ToString() : "";
 
                string zipCode = (item["ZipCode"].Controls[0] as TextBox).Text;
 
                GridEditFormItem editFormItem = (GridEditFormItem)e.Item;
                RadComboBox tobaccoUsageCombo = (RadComboBox)editFormItem.FindControl("TobaccoUsageComboBox");
                RadComboBox wellnessFactorCombo = (RadComboBox)editFormItem.FindControl("WellnessFactorComboBox");
                RadComboBox medicalCombo = (RadComboBox)editFormItem.FindControl("MedicalClassComboBox");
                RadComboBox dentalCombo = (RadComboBox)editFormItem.FindControl("DentalClassComboBox");
                ParentChild parentChild = new ParentChild(id, "name", Convert.ToDateTime(DOB), zipCode,
                    tobaccoUsageCombo.SelectedValue,wellnessFactorCombo.SelectedValue,
                    medicalCombo.SelectedValue, medicalDentalClass[medicalCombo.SelectedValue],
                    dentalCombo.SelectedValue, medicalDentalClass[dentalCombo.SelectedValue]
                    );
 
                listParentChild.Add(parentChild);
            }
            else if (e.Item.OwnerTableView.Name == "Child")
            {
                string parentID = e.Item.OwnerTableView.ParentItem.GetDataKeyValue("ID").ToString();
                RadDatePicker picker = (item["DependentDOB"].Controls[0] as RadDatePicker);
                string DOB = picker.SelectedDate != null ? picker.SelectedDate.Value.ToString() : "";
                GridEditFormItem editFormItem = (GridEditFormItem)e.Item;
                RadComboBox tobaccoUsageCombo = (RadComboBox)editFormItem.FindControl("DependentTobaccoUsageComboBox");
                RadComboBox wellnessFactorCombo = (RadComboBox)editFormItem.FindControl("DependentWellnessFactorComboBox");
                int id = CreateNewChildId(Convert.ToInt32(parentID));
 
                Child child = new Child(id, Convert.ToDateTime(DOB),
                                    tobaccoUsageCombo.SelectedValue, wellnessFactorCombo.SelectedValue);
 
                ParentChild parentChild = listParentChild.Where(pc => pc.ID == Convert.ToInt32(parentID)).Single();
                parentChild.listChild.Add(child);
            }
            ViewState["listParentChild"] = listParentChild;
        }
 
        protected void RadGrid1_EditCommand(object sender, GridCommandEventArgs e)
        {
            //// ******* need to close any outstanding Add form ************
            //RadGrid1.MasterTableView.IsItemInserted = false;
 
            //if (e.Item.OwnerTableView.Name == "Child")
            //{
            //    //e.Item.OwnerTableView.ParentItem.RemoveChildEditItems();
            //    e.Item.RemoveChildEditItems();
            //    //RadGrid1.MasterTableView.IsItemInserted = false;
            //}
 
            //e.Item.OwnerTableView.IsItemInserted = false;
 
            //RadGrid1.MasterTableView.ClearEditItems();
        }
 
        protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            string strId = item.GetDataKeyValue("ID").ToString();
            if (e.Item.OwnerTableView.Name == "Parent")
            {
                RadDatePicker picker = (item["DOB"].Controls[0] as RadDatePicker);            
                string DOB = picker.SelectedDate != null ? picker.SelectedDate.Value.ToString() : "";
 
                string zipCode = (item["ZipCode"].Controls[0] as TextBox).Text;
 
                GridEditFormItem editFormItem = (GridEditFormItem)e.Item;
                RadComboBox tobaccoUsageCombo = (RadComboBox)editFormItem.FindControl("TobaccoUsageComboBox");
                RadComboBox wellnessFactorCombo = (RadComboBox)editFormItem.FindControl("WellnessFactorComboBox");
                RadComboBox medicalCombo = (RadComboBox)editFormItem.FindControl("MedicalClassComboBox");
                RadComboBox dentalCombo = (RadComboBox)editFormItem.FindControl("DentalClassComboBox");
 
                ParentChild parentChild = listParentChild.Where(pc => pc.ID == Convert.ToInt32(strId)).Single();
                parentChild.DOB = Convert.ToDateTime(DOB);
                parentChild.ZipCode = zipCode;
                parentChild.TobaccoUsage = tobaccoUsageCombo.SelectedValue;
                parentChild.WellnessFactor = wellnessFactorCombo.SelectedValue;
                parentChild.MedicalClass = medicalCombo.SelectedValue;
                parentChild.MedicalClassDisplay = medicalDentalClass[medicalCombo.SelectedValue];
                parentChild.DentalClass = dentalCombo.SelectedValue;
                parentChild.DentalClassDisplay = medicalDentalClass[dentalCombo.SelectedValue];
            }
            else if (e.Item.OwnerTableView.Name == "Child")
            {
                string parentID = e.Item.OwnerTableView.ParentItem.GetDataKeyValue("ID").ToString();
                RadDatePicker picker = (item["DependentDOB"].Controls[0] as RadDatePicker);
                string DOB = picker.SelectedDate != null ? picker.SelectedDate.Value.ToString() : "";
                GridEditFormItem editFormItem = (GridEditFormItem)e.Item;
                RadComboBox tobaccoUsageCombo = (RadComboBox)editFormItem.FindControl("DependentTobaccoUsageComboBox");
                RadComboBox wellnessFactorCombo = (RadComboBox)editFormItem.FindControl("DependentWellnessFactorComboBox");
                 
                ParentChild parentChild = listParentChild.Where(pc => pc.ID == Convert.ToInt32(parentID)).Single();
                Child child = parentChild.listChild.Where(c => c.ID == Convert.ToInt32(strId)).Single();
                child.DependentDOB = Convert.ToDateTime(DOB);
                child.DependentTobaccoUsage = tobaccoUsageCombo.SelectedValue;
                child.DependentWellnessFactor = wellnessFactorCombo.SelectedValue;
            }
            ViewState["listParentChild"] = listParentChild;
        }
 
        protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GridDataItem item = e.Item as GridDataItem;
            string strId = item.GetDataKeyValue("ID").ToString();
 
            if (e.Item.OwnerTableView.Name == "Parent")
            {
                ParentChild parentChild = listParentChild.Where(pc => pc.ID == Convert.ToInt32(strId)).Single();
                listParentChild.Remove(parentChild);
            }
            else if (e.Item.OwnerTableView.Name == "Child")
            {
                string parentID = e.Item.OwnerTableView.ParentItem.GetDataKeyValue("ID").ToString();
                ParentChild parentChild = listParentChild.Where(pc => pc.ID == Convert.ToInt32(parentID)).Single();
                Child child = parentChild.listChild.Where(c => c.ID == Convert.ToInt32(strId)).Single();
                parentChild.listChild.Remove(child);              
            }
            ViewState["listParentChild"] = listParentChild;
        }
 
        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            GridEditableItem item = e.Item as GridEditableItem;
 
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                if (e.Item.OwnerTableView.Name == "Parent")
                {
                    RegularExpressionValidator regValidator = new RegularExpressionValidator();
                    regValidator.ID = "regValidator";
                    regValidator.ControlToValidate = (item["ZipCode"].Controls[0] as TextBox).ID;
                    regValidator.ValidationExpression = @"\d{5}";
                    regValidator.ErrorMessage = "*ZIP code must be 5 numeric digit";
                    regValidator.ForeColor = System.Drawing.Color.Red;
                    item["ZipCode"].Controls.Add(regValidator);
                }
                else if (e.Item.OwnerTableView.Name == "Child")
                {
                }
            }
        }
 
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            //if (e.CommandName == "InitInsert")
            //{
            //    // ******* need to close any outstanding Add form ************
            //    //RadGrid1.MasterTableView.IsItemInserted = false;
 
            //    RadGrid1.MasterTableView.ClearEditItems();
            //    if (e.Item.OwnerTableView.Name == "Child")
            //    {
            //        e.Item.OwnerTableView.ParentItem.RemoveChildEditItems();
            //        //RadGrid1.MasterTableView.IsItemInserted = false;
            //    }
            //}
        }
 
 
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
            {
                //Clear and reset all outstanding edit form
                e.Item.OwnerTableView.IsItemInserted = false;
                e.Item.OwnerTableView.ClearEditItems();
                e.Item.OwnerTableView.ClearChildEditItems();
                 
                GridEditableItem item = e.Item as GridEditableItem;
                if (e.Item.OwnerTableView.Name == "Parent")
                {
                    RadDatePicker picker = (item["DOB"].Controls[0] as RadDatePicker);
                    picker.MaxDate = DateTime.Now;
 
                    if (item.ItemIndex != -1)
                    {
                        GridEditFormItem editFormItem = (GridEditFormItem)e.Item;
                        RadComboBox tobaccoUsageCombo = (RadComboBox)editFormItem.FindControl("TobaccoUsageComboBox");
                        RadComboBox wellnessFactorCombo = (RadComboBox)editFormItem.FindControl("WellnessFactorComboBox");
                        RadComboBox medicalCombo = (RadComboBox)editFormItem.FindControl("MedicalClassComboBox");
                        RadComboBox dentalCombo = (RadComboBox)editFormItem.FindControl("DentalClassComboBox");
 
                        if (item.GetDataKeyValue("TobaccoUsage") != null)
                            tobaccoUsageCombo.SelectedValue = item.GetDataKeyValue("TobaccoUsage").ToString();
                        if (item.GetDataKeyValue("WellnessFactor") != null)
                            wellnessFactorCombo.SelectedValue = item.GetDataKeyValue("WellnessFactor").ToString();
                        if (item.GetDataKeyValue("MedicalClass") != null)
                            medicalCombo.SelectedValue = item.GetDataKeyValue("MedicalClass").ToString();
                        if (item.GetDataKeyValue("DentalClass") != null)
                            dentalCombo.SelectedValue = item.GetDataKeyValue("DentalClass").ToString();
                    }
                }
                else if (e.Item.OwnerTableView.Name == "Child")
                {
                    RadDatePicker picker = (item["DependentDOB"].Controls[0] as RadDatePicker);
                    picker.MaxDate = DateTime.Now;
 
                    if (item.ItemIndex != -1)
                    {
                        GridEditFormItem editFormItem = (GridEditFormItem)e.Item;
                        RadComboBox tobaccoUsageCombo = (RadComboBox)editFormItem.FindControl("DependentTobaccoUsageComboBox");
                        RadComboBox wellnessFactorCombo = (RadComboBox)editFormItem.FindControl("DependentWellnessFactorComboBox");
 
                        if (item.GetDataKeyValue("DependentTobaccoUsage") != null)
                            tobaccoUsageCombo.SelectedValue = item.GetDataKeyValue("DependentTobaccoUsage").ToString();
                        if (item.GetDataKeyValue("DependentWellnessFactor") != null)
                            wellnessFactorCombo.SelectedValue = item.GetDataKeyValue("DependentWellnessFactor").ToString();
                    }
                }
            }
        }
    }
}

Here is the designer.cs file

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
 
namespace TestWebTelerik {
     
     
    public partial class _Default {
         
        /// <summary>
        /// RadScriptManager1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Telerik.Web.UI.RadScriptManager RadScriptManager1;
         
        /// <summary>
        /// RadAjaxManager1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Telerik.Web.UI.RadAjaxManager RadAjaxManager1;
         
        /// <summary>
        /// RadAjaxPanel1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Telerik.Web.UI.RadAjaxPanel RadAjaxPanel1;
         
        /// <summary>
        /// RadGrid1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Telerik.Web.UI.RadGrid RadGrid1;
    }
}

1 Answer, 1 is accepted

Sort by
0
Marin
Telerik team
answered on 06 Aug 2013, 12:06 PM
Hello,

 Here are suggestions for each question:

1. Setting different validation groups is indeed the preferred approach to distinguish validations in multiple forms. You can either use a separate edit form for the grid where you define and have access to all controls as shown in this online demo or directly access the autogenerated link buttons in the default edit form as shown in this help topic. Once you access the insert/cancel buttons you can set their preferred validation group.
2. Normally if the MultiRowEdit feature is not enabled the grid keeps only a single row in edit mode (even in the case of hierarchy and child tables). Also if another row goes in edit mode the previously expanded items will be closed unless explicitly persisted. Having this in mind the only possible cases where you can have more than one Edit/Insert form open is when one or more insert forms are open and there is a row in edit mode. This way you can either close the edit row if the previous action was an InitInsert command or close all insert forms if the grid is initiating an EditCommand. Below is a sample code demonstrating how you can achieve this behavior (note that in this case you do not need additional code the ItemDataBound event). Also keep in mind the above approach has some limitations because when you close an insert form a rebind of the relevant GridTableView is required. However when this tableView is the MasterTableView the rebind also closes all expanded items so if you open and insert form from a child table and you need to close an insert form in the masterTableView the row for the current table view will also get collapsed and you won't see the new insert form open which leads to undesired user experience. To prevent this from happening another option is to persists the expanded and collapsed rows and restore them on PreRender as well as put the respective detail table view back in insert mode after rebinding the master table view to close the insert form.

string commandName = "";
    GridTableView currentTableView = null;
 
    protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
    {
        commandName = e.CommandName;
        currentTableView = e.Item.OwnerTableView;
    }
 
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (commandName == RadGrid.InitInsertCommandName)
        {
            if (RadGrid1.EditIndexes.Count > 0)
            {
                RadGrid1.MasterTableView.ClearEditItems();
            }
            List<GridTableView> tableViews = new List<GridTableView>();
            //tableViews.Add(RadGrid1.MasterTableView);
            foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
            {
                if (dataItem.Expanded)
                {
                    tableViews.Add(dataItem.ChildItem.NestedTableViews[0]);
                }
            }
 
            foreach (var tableView in tableViews)
            {
                if (tableView != currentTableView && tableView.IsItemInserted)
                {
                    tableView.IsItemInserted = false;
                    tableView.Rebind(); //should not rebind the master table view here
                }
            }
             
        }
 
        if (commandName == RadGrid.EditCommandName && RadGrid1.MasterTableView.IsItemInserted)
        {
            RadGrid1.MasterTableView.IsItemInserted = false;
            currentTableView.IsItemInserted = false;
            RadGrid1.Rebind();
        }
    }

Note that the above code will still allow to have two items in insert mode - one on the MasterTableView and another on a child table view because of the aforementioned limitations.

3. This problem should have been fixed in the latest version of the control so you can upgrade and check out how it works in your case.

Regards,
Marin
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
Tags
Grid
Asked by
Yoong
Top achievements
Rank 1
Answers by
Marin
Telerik team
Share this question
or