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

Grid with Tree view problem

1 Answer 124 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Sucheta Patil
Top achievements
Rank 1
Sucheta Patil asked on 25 Feb 2011, 06:08 PM
Hi
I have a radgrid and i am trying to use treeview under radgrid.
Similar to your demo example http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridwithtreeviewcomboboxeditors/defaultcs.aspx?product=grid

But I cant get it to work.
I want a empty grid in which onClick of 'Add New Record' I want toinsert into tblPettyCash.
I have a table tblExpCodes with fields

ExpType
Category
ExpCodeDesc only to display data.

I want to have tree view for these fields and only select them NOT to update anything on tblExpCodes table.
I use tblPettyCash to enter Claims.
The demo is slightly complicated 
I created a similar .aspx page but giving me error saying

These columns don't currently have unique values.


I have attached the code files.
<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/CWCStaffnet.Master" CodeBehind="Petty.aspx.cs" Inherits="CWC.Staffnet.Forms.Finance.Petty" %>
  
<%@ MasterType VirtualPath="~/CWCStaffnet.Master" %>
  
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link href="../Styles/Styles.css" rel="stylesheet" type="text/css" /> 
    <script type="text/javascript"  src="../JSValidation.js"></script>       
    <style type="text/css">
        .MyImageButton
        {
           cursor: hand;
        }
        .EditFormHeader td
        {
            font-size: 14px;
            padding: 4px !important;
            color: #0066cc;
        }
        </style>
  
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <h1>Petty Cash Claim Form</h1>
      
    <asp:Panel ID="plForm" runat="server">
     <telerik:RadAjaxLoadingPanel ID="LoadingPanel1" runat="server" IsSticky="True" Style="position: absolute;  top: 0; left: 0; height: 100%; width: 100%;" >
        </telerik:RadAjaxLoadingPanel>
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
  
            <script type="text/javascript">
                function RowDblClick(sender, eventArgs) {
                    sender.get_masterTableView().editItem(eventArgs.get_itemIndexHierarchical());
                }
            </script>
  
        </telerik:RadCodeBlock>
         <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
        <script type="text/javascript">
  
            //stop the event bubbling
            function StopPropagation(e) {
                if (!e) {
                    e = window.event;
                }
  
                e.cancelBubble = true;
            }
  
            //find the selected node in the treeview inside the combobox and scroll it into view
            function OnClientDropDownOpenedHandler(sender, eventArgs) {
                var tree = sender.get_items().getItem(0).findControl("RadTreeView1");
                var selectedNode = tree.get_selectedNode();
  
                if (selectedNode) {
                    selectedNode.scrollIntoView();
                }
            }
            //when tree node is clicked, set the text and value for the item in the combobox and commit the changes 
            function nodeClicking(sender, args) {
  
                //get the id of the employeesCombo in the edited row (passed from the server in the ItemDataBound event handler) 
                var comboBox = $find(window['comboId']);
                var node = args.get_node();
  
                comboBox.set_text(node.get_text());
  
                comboBox.trackChanges();
                comboBox.get_items().getItem(0).set_text(node.get_text());
                comboBox.get_items().getItem(0).set_value(node.get_value());
                comboBox.commitChanges();
  
                comboBox.hideDropDown();
                comboBox.attachDropDown();
            }
              
        </script>
    </telerik:RadScriptBlock>
  
 <asp:Label ID="Label1" runat="server" EnableViewState="false" Font-Bold="true" Text="Orders List" />
    <telerik:RadGrid ID="RadGrid1" AutoGenerateColumns="false" PageSize="15" AllowPaging="true"
        AllowSorting="true" runat="server" DataSourceID="LinqPettyCash" AllowAutomaticUpdates="true"
        AllowAutomaticInserts="True" ShowStatusBar="true" OnItemCreated="RadGrid1_ItemCreated"
        OnUpdateCommand="RadGrid1_UpdateCommand" >
        <MasterTableView DataKeyNames="Id" EditMode="InPlace" CommandItemDisplay="TopAndBottom" DataSourceID="LinqPettyCash"
            TableLayout="Fixed">
            <Columns>
                <telerik:GridBoundColumn UniqueName="Id" DataField="Id" HeaderText="Id"
                    ReadOnly="true" />
                    <telerik:GridTemplateColumn UniqueName="Code" HeaderText="Code" SortExpression="Code"
                    ItemStyle-Width="400px">
                    <ItemTemplate>
                        <%#DataBinder.Eval(Container.DataItem, "ExpenditureCode")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <!-- Show employees in the treeview -->
                        <telerik:RadComboBox ID="RadComboBox1" runat="server" Width="180px"
                            ShowToggleImage="True" Style="vertical-align: middle;" OnClientDropDownOpened="OnClientDropDownOpenedHandler"
                            ExpandAnimation-Type="None" CollapseAnimation-Type="None">
                            <ItemTemplate>
                                <div id="div1" onclick="StopPropagation(event);">
                                    <telerik:RadTreeView runat="server" ID="RadTreeView1" OnClientNodeClicking="nodeClicking"
                                        Height="140px" DataTextField="ExpenditureCode" DataValueField="CodeDescription" DataFieldID="CodeDescription"
                                        DataFieldParentID="ExpType" DataSourceID="ExpDataSource" />
                                </div>
                            </ItemTemplate>
                            <Items>
                                <telerik:RadComboBoxItem Text="" />
                            </Items>
                        </telerik:RadComboBox>
                    </EditItemTemplate>
                </telerik:GridTemplateColumn>
                </Columns>
        </MasterTableView>
    </telerik:RadGrid>
     <asp:Label ID="lblMessage" runat="server" EnableViewState="false" Font-Bold="true" />
  
     <br />
                 <p><asp:Label ID="lbError" runat="server" CssClass="message" Visible="false"></asp:Label></p>
                 <asp:ValidationSummary runat="server" ID="validationSummary3" ValidationGroup="Fault" /> 
                   <asp:Button ID="btSubmit" runat="server" CausesValidation="true" 
                       OnClick="btSubmit_Click" Text="Submit" ValidationGroup="Fault" />
  
     <asp:SqlDataSource ID="ExpDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:cwc_staffnetConnectionString %>"
        SelectCommand="SELECT DISTINCT Category,Id,CodeDescription, ExpenditureCode,ExpCodeDesc,ExpType  FROM tblExpenditureCodes" 
         InsertCommand="INSERT INTO tblPettyCashes ([ExpenditureCode], [ExpType],[Id]) VALUES (@ExpenditureCode, @ExpType, @Id)"
  
        />
         <asp:LinqDataSource ID="LinqPettyCash" runat="server" 
            ContextTypeName="CWC.Staffnet.Forms.StaffnetDataContext" 
            TableName="tblPettyCashes" EnableDelete="True" 
            EnableUpdate="True" EnableInsert="true" >
        </asp:LinqDataSource>  
        </asp:Panel>
    <asp:Panel ID="plConfirm" runat="server" Visible="false">
    <table>  
  <tr>
    <td
        <p><b>Notification of Petty example Form.</b></p>
        <p>
            You have successfully completed the Petty cash Claim form. </p>            
        <p>       
            For any questions or comments regarding this form please contact 
            <a href="mailto:online.services@cwc.ac.uk"> Online services </a>
            Thank you.</p>
        </td>         
        </tr>
</table>
    </asp:Panel>
     <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="plfrm">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl LoadingPanelID="LoadingPanel1" ControlID="RadGrid1"/>
                        <telerik:AjaxUpdatedControl ControlID="RadWindowManager1" />
                        <telerik:AjaxUpdatedControl LoadingPanelID="LoadingPanel1" ControlID="lstName" />
                        <telerik:AjaxUpdatedControl LoadingPanelID="LoadingPanel1" ControlID="lstFaculty" />   
                        <telerik:AjaxUpdatedControl LoadingPanelID="LoadingPanel1" ControlID="lstCentre" />   
                    </UpdatedControls>
                </telerik:AjaxSetting>
                 
            </AjaxSettings>
        </telerik:RadAjaxManager>
</asp:Content>
  
  
******************************************************************************************************************************
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using Telerik.Web.UI;
using config = CWC.Staffnet.Forms.Properties.Settings;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System;
  
  
namespace CWC.Staffnet.Forms.Finance
{
    public partial class Petty : System.Web.UI.Page
    {
        private StaffnetDataContext dc;      
        protected void Page_Init(object sender, EventArgs e)
        {
            dc = new StaffnetDataContext();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
  
        }
        protected void btSubmit_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                try
                {
                    AddRecord();
                    SendEmail();
                    plConfirm.Visible = true;
                    plForm.Visible = false;
                }
                catch (Exception ex)
                {
                    ShowErrorMessage(ex.ToString());
                }
            }
            else
            {
                string msg = string.Empty;
                foreach (IValidator validator in this.Validators)
                {
                    if (!validator.IsValid)
                    {
                        msg += String.Format("{0}<br/>", validator.ErrorMessage);
                        ShowErrorMessage(msg);
                    }
                }
            }
        }
        private void ShowErrorMessage(string ex)
        {
            lbError.Text = ex.ToString();
            lbError.Visible = true;
        }
        private void AddRecord()
        { }
        private void SendEmail()
        { }
        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            //if a grid item is in edit mode, wire the ItemsRequested event of the customersCombo to filter the items in it based on the selection in the freight combo
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                RadComboBox freightCombo = (e.Item as GridEditableItem)["Code"].Controls[0] as RadComboBox;
  
                if (Page.IsCallback)
                {
                      
                }
            }
        }
  
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridEditableItem)
            {              
  
                //set the selected value for the Employees combobox to match the value in the edited cell
                RadComboBox employeesCombo = (e.Item as GridEditableItem).FindControl("RadComboBox1") as RadComboBox;
                employeesCombo.Items[0].Text = DataBinder.Eval(e.Item.DataItem, "ExpenditureCode").ToString();
  
                //set the selection in the treeview inside the combobox to match the value in the edited cell
                RadTreeView employeesTreeView = employeesCombo.Items[0].FindControl("RadTreeView1") as RadTreeView;
                employeesTreeView.FindNodeByText(DataBinder.Eval(e.Item.DataItem, "ExpenditureCode").ToString()).Selected = true;
                //Expand all nodes to scroll the selected into view. Have in mind that load-on-demand is recommended with very large number of nodes in the treeview 
                employeesTreeView.ExpandAllNodes();
  
                //register script block which holds the client id of the employeesComboBox. Will be used to reference the client object of the combobox in the RadTreeView's OnClientNodeClicking event handler
                RadScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "employeesComboScript", "<script type='text/javascript'>window['comboId'] = '" + e.Item.FindControl("RadComboBox1").ClientID + "';</script>", false);
  
            }
             
        }
        protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            string empId = (((e.Item as GridEditableItem).FindControl("RadComboBox1") as RadComboBox).Items[0].FindControl("RadTreeView1") as RadTreeView).SelectedNode.Value;
  
            //if the EmployeeID value is empty, cancel the update operation
            if (empId == string.Empty)
            {
                e.Canceled = true;
                SetMessage("Order cannot be updated. You must select an employee from the provided list");
            }
            else
            {
                LinqPettyCash.UpdateParameters["Id"].DefaultValue = empId;
            }
        }
        public void SetMessage(string message)
        {
            lblMessage.Text = message;
        }
  
    }
}

If you could help me quickly.
Thankyou
Suchi



1 Answer, 1 is accepted

Sort by
0
Pavlina
Telerik team
answered on 03 Mar 2011, 01:23 PM
Hi Sucheta,

Most probably you are getting this error because you have not assigned the unique identifier to the DataFieldID of Treeview. In your case the DataFieldID is 'CodeDescription', can you please verify that it is a unique field in your database?

For more information on this please refer the following documentation.
Binding to Hierarchical Data

Best wishes,
Pavlina
the Telerik team
Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
Tags
Grid
Asked by
Sucheta Patil
Top achievements
Rank 1
Answers by
Pavlina
Telerik team
Share this question
or