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

Extracting primary key value for parent item in hierarchy on Insert with User Control EditForm and MasterPage

5 Answers 223 Views
Grid
This is a migrated thread and some comments may be shown as answers.
David Kingston
Top achievements
Rank 2
David Kingston asked on 30 Oct 2009, 03:51 AM

Here's my setup:  I have a MasterPage that has a webform with a RadGrid in it.  That RadGrid has one nested table.  I'm trying to insert a new item into that nested table using a WebUserControl (ascx) page as the EditForm for the nested Grid.

I've read the help at: http://www.telerik.com/help/aspnet-ajax/grdextractprimarykeyforparentiteminhierarchyonupdateinsert.html

My grid and nested grid are setup pretty much identically to what is there, except that I'm using a MasterPage and usercontrol for the form and I have a dataobject for the datasource.

When updating the nested grid with the usercontrol, the world is a wonderful place and things work just fine.  However, when that same form is used for inserting, the binding values go away.  In the customers and orders example, the customerID is not set to the default for the primarykey of the parent item.

I tried the code from http://www.telerik.com/help/aspnet-ajax/grdcustomeditforms.html for accessing the grid edited item from the usercontrol. 

GridEditableItem editedItem = this.Parent.NamingContainer; 

It generates a compiler error (cannot implictly convert system.web.ui.control to telerik.web.ui.GridEditableItem.  An explict conversion exists).  When I explictly cast, editedItem.KeyValues is null.  I think this may be something funky with the masterpages.

If parentID is an int32, I can use the following code in the main aspx code behind to get the appropriate value:

public int parentID {get; set;}
if
 (e.CommandName == RadGrid.InitInsertCommandName)  
            {  
                if (e.Item.OwnerTableView.DataSourceID == "OrderLookup")  
                {  
                    GridDataItem parentItem = (GridDataItem)(e.Item.OwnerTableView.ParentItem);  
                    if (parentItem != null)  
                    {  
                        parentID = (Convert.ToInt32((parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex]["CustomerID"])));  
                    }  
                }  
            } 

But I can not for the life of me access that value from the ascx page.  I'm also assuming this is because of some masterpage stuff that I haven't figured out yet.

So, How can I reference that DataKeyValue from the WebUserControl for an insert function?  I need to set the default value for the customerID.  What is the best way to accomplish this?

5 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 1
answered on 30 Oct 2009, 05:35 AM

Hello David ,

Here's an example of how to access the parent item of a child record while inserting and set the property of the user control with a field value of the parent item:

protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)    
    {    
        if (e.Item is GridEditFormInsertItem && e.Item.OwnerTableView.IsItemInserted && e.Item.OwnerTableView.Name == "Detail")    
        {    
            GridEditFormInsertItem insertItem = (GridEditFormInsertItem)e.Item;                
            MyUserControl usercntrl = (MyUserControl)insertItem.FindControl(GridEditFormItem.EditFormUserControlID);    
            GridDataItem parentItem = (GridDataItem)insertItem.ParentItem;    
            int parentID =(Convert.ToInt32((parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex]["CustomerID"])));   
            usercntrl.ParentID = parentID ;    
        }    
    }   
 


Thanks
Princy

0
David Kingston
Top achievements
Rank 2
answered on 30 Oct 2009, 03:01 PM
Took me a while to get this hooked up and figure out what is going on.
I have added the ItemDataBound event, and verified that it fires.  I also verify that the if statement containing the three conditions fires.

On stepping through things, I run into an error.  insertItem.ParentItem is null.  insertItem has the value of Telerik.Web.UI.GridEditFormInsertItem.  But the value for ParentItem is null.  Why would this be the case?  I assume that I have something configured wrong.
0
David Kingston
Top achievements
Rank 2
answered on 30 Oct 2009, 03:30 PM
Ok, if I change the line from:
GridDataItem parentItem = (GridDataItem)insertItem.ParentItem;

to:
GridDataItem parentItem = (GridDataItem)e.Item.OwnerTableView.ParentItem;

I get the correct value.  However, when I try to use that value in the usercontrol page on the button event for save, I have a value of 0.  It's like the value is lost when the RadGrid loads the usercontrol.

 

Edit:
Thanks for the help.  Maybe I should be clearer about what is going on.  I handle the insert event from the button click event of the user control.  So when the button clicks it fires the on_click event in the user control where I attach values to my object and save it.  I need the CustomerID available in that event.  Or I need to understand the model for handling the insert event in the page with the grid (aspx) with access to the new values from the user control form.

Here's the code to help:
I've changed the names of things to make the example easier.  I think I got it all  Here is the page Customers.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Customers.aspx.cs" Inherits="CMDB.MasterGrid.CustomerGrid" %> 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik"%> 
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent1" runat="server">  
 <telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server">  
    <AjaxSettings> 
        <telerik:AjaxSetting AjaxControlID="CustomerRadGrid">  
            <UpdatedControls> 
                <telerik:AjaxUpdatedControl ControlID="CustomerRadGrid" /> 
            </UpdatedControls> 
        </telerik:AjaxSetting> 
    </AjaxSettings> 
</telerik:RadAjaxManagerProxy> 
<telerik:RadGrid ID="CustomerRadGrid"   
        runat="server" 
        AutoGenerateColumns="False" 
        DataSourceID="SqlDataViewCustomerLookup"   
        GridLines="None" 
        AllowPaging="True"   
        onprerender="CustomerRadGrid_PreRender"   
        onitemcommand="CustomerRadGrid_ItemCommand" 
        EnableLinqExpressions="false"   
        onitemdatabound="CustomerRadGrid_ItemDataBound" > 
<MasterTableView DataSourceID="SqlDataViewCustomerLookup" AllowSorting="true" DataKeyNames="CustomerID" CommandItemDisplay="Top"   
    OverrideDataSourceControlSorting="true" AllowFilteringByColumn="true" EditMode="EditForms" Name="MainCustomer">  
            <DetailTables> 
        <telerik:GridTableView Name="OrdersGrid" ShowFooter="false" AllowFilteringByColumn="false" EditMode="EditForms" Width="98%" DataKeyNames="OrderID"  DataSourceID="OrderLookup"  CommandItemDisplay="Top" BorderWidth="1" runat="server">  
            <ParentTableRelation> 
                <telerik:GridRelationFields DetailKeyField="CustomerID"  MasterKeyField="CustomerID" /> 
            </ParentTableRelation> 
 
            <RowIndicatorColumn> 
                <HeaderStyle Width="5px"></HeaderStyle> 
            </RowIndicatorColumn> 
            <ExpandCollapseColumn> 
                <HeaderStyle Width="5px"></HeaderStyle> 
            </ExpandCollapseColumn> 
            <Columns> 
                   <telerik:GridEditCommandColumn> 
                   </telerik:GridEditCommandColumn> 
                   <telerik:GridBoundColumn DataField="OrderID" DataType="System.Int32" HeaderText="OrderID" UniqueName="OrderID" Visible="False" /> 
                   <telerik:GridBoundColumn DataField="CustomerID" DataType="System.Int32" HeaderText="CustomerID" UniqueName="CustomerID" Visible="False" /> 
                   <telerik:GridBoundColumn DataField="OrderNotes" HeaderText="Notes" UniqueName="OrderNotes" /> 
                                 </Columns> 
                
            <SortExpressions> 
            <telerik:GridSortExpression FieldName="OrderID"></telerik:GridSortExpression> 
            </SortExpressions> 
 
<EditFormSettings EditFormType="WebUserControl" UserControlName="~/UserControls/OrderEdit.ascx">  
<EditColumn UniqueName="EditCommandColumn2" ></EditColumn>  
<FormTemplate> 
              
        </FormTemplate> 
 
</EditFormSettings> 
        </telerik:GridTableView> 
    </DetailTables>           
              
<RowIndicatorColumn> 
<HeaderStyle Width="20px"></HeaderStyle> 
</RowIndicatorColumn> 
 
<ExpandCollapseColumn> 
<HeaderStyle Width="20px"></HeaderStyle> 
</ExpandCollapseColumn> 
    <Columns> 
        <telerik:GridEditCommandColumn> 
        </telerik:GridEditCommandColumn> 
        <Telerik:GridBoundColumn datafield="CustomerID" datatype="System.Int32"   
            headertext="CustomerID" readonly="True" sortexpression="CustomerID"   
            uniquename="CustomerID" Visible="False"></Telerik:GridBoundColumn> 
        <Telerik:GridBoundColumn datafield="CustomerName" headertext="Customer Name"   
             sortexpression="CustomerName" uniquename="CustomerName"></Telerik:GridBoundColumn> 
          
    </Columns> 
        <EditFormSettings EditFormType="WebUserControl">  
        <EditColumn UniqueName="EditCommandColumn1"></EditColumn> 
 
          </EditFormSettings> 
            <PagerStyle Mode="NextPrevAndNumeric" /> 
</MasterTableView> 
 
 
    </telerik:RadGrid> 
       
    <asp:SqlDataSource ID="SqlDataViewCustomerLookup" runat="server"   
        ConnectionString="<%$ ConnectionStrings:CMDBConnectionString %>"   
        SelectCommand="SELECT * FROM [ViewCustomerLookups]"></asp:SqlDataSource> 
          
            <asp:SqlDataSource ID="OrderLookup" runat="server"   
                ConnectionString="<%$ ConnectionStrings:CMDBConnectionString %>"   
                SelectCommand="SELECT * FROM [ViewOrderLookups] WHERE (CustomerID = @CustomerID)">  
                    <SelectParameters> 
                        <asp:QueryStringParameter Name="CustomerID" QueryStringField="CustomerID"   
                            Type="Int32" /> 
                    </SelectParameters> 
             </asp:SqlDataSource> 
      
          
          
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="Navigation" runat="server">  
</asp:Content> 
 

 

Here is the code behind for that page:

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;  
using Telerik.Web.Design;  
 
namespace CMDB.MasterGrid  
{  
    public partial class CustomerGrid : System.Web.UI.Page  
    {  
       public int ID {getset;}          
        protected void Page_Load(object sender, EventArgs e)  
        {  
             
        }  
 
        protected void CustomerRadGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)  
        {  
            if (e.Item is GridEditFormInsertItem && e.Item.OwnerTableView.IsItemInserted && e.Item.OwnerTableView.Name == "OrdersGrid")  
            {  
                GridEditFormInsertItem insertItem = (GridEditFormInsertItem)e.Item;  
                UserControls.OrderEdit usercntrl = (UserControls.OrderEdit)insertItem.FindControl(GridEditFormItem.EditFormUserControlID);  
                GridDataItem parentItem = (GridDataItem)e.Item.OwnerTableView.ParentItem;  
                int ID = (Convert.ToInt32((parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex]["CustomerID"])));  
                usercntrl.parentID = ID; 
                  
            }    
 
        }     
 
        protected void ServerRadGrid_ItemCommand(object source, GridCommandEventArgs e)  
        {  
        //I left out the stuff that deals with the parent grid setting edit and insert user controls since that stuff works fine. 
        }  
 
    }  
 

 
When I step through this, usercntrl.parentID will be the correct value.
So then I have a ascx page called OrderEdit with a form and a button.  I didn't include it as it's just a form and a button.  If you think that's the problem let me know and I'll post it.  Here is the code behind for that page:

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 CMDB.UserControls  
{  
    public partial class OrderEdit : System.Web.UI.UserControl  
    {  
        public int parentID {getset;}  
        protected void Page_Load(object sender, EventArgs e)  
        {  
              
        }  
 
        protected void btnUpdate_Click(object sender, EventArgs e)  
        {  
         //This part works great.     
         if (btnUpdate.Text == "Update")  
            {  
                CMDB.Order order = new CMDB.Order(Convert.ToInt32(lblID.Text));  
                order.CustomerID = (Convert.ToInt32(lblCustomerID.Text));  
                order.OrderNotes = tbNotes.Text;  
                order.Save(Page.User.Identity.Name.ToString());  
             }  
            if (btnUpdate.Text == "Insert")  
            {  
                //This works not at all.  
                CMDB.Order order = new CMDB.Order();  
                order.CustomerID = parentID;  //parentID has a value of 0 here when it has a value of 1 on the aspx page.  
                order.OrderNotes = tbNotes.Text;  
                power.Save(Page.User.Identity.Name.ToString());  
            }  
        }  
 
    }  
0
Accepted
Princy
Top achievements
Rank 1
answered on 02 Nov 2009, 07:27 AM
Hi David,

For your scenario, the approach provided by Telerik in the help document would be an appropriate solution, just that you would have to modify it slightly as shown below:
ascx.cs:
 protected void Page_Load(object sender, EventArgs e) 
    { 
 
        GridEditableItem editedItem = (GridEditableItem)this.Parent.NamingContainer; 
        GridDataItem parentItem = (GridDataItem)editedItem.OwnerTableView.ParentItem; 
        TextBox1.Text = parentItem.GetDataKeyValue["PrimaryKeyField"].ToString(); 
    } 

Thanks
Princy.
0
David Kingston
Top achievements
Rank 2
answered on 03 Nov 2009, 03:29 PM

Sorry I didn't get around to testing this solution until this AM.

The syntax on the last line of the page_load was giving me errors about using index[] on the method.  So I changed that line to be the following:

parentID = (Convert.ToInt32(parentItem.GetDataKeyValue("PrimaryKeyField").ToString()));

 

And everything is working well.  Thanks for your time and help.

Tags
Grid
Asked by
David Kingston
Top achievements
Rank 2
Answers by
Princy
Top achievements
Rank 1
David Kingston
Top achievements
Rank 2
Share this question
or