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

Self reference and load on demand at Simple File Explorer

8 Answers 150 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Robert
Top achievements
Rank 1
Robert asked on 14 Feb 2011, 12:20 PM

Hello,

I use:

  • Q3 2010 version 2010.3.10.1215
  • Windows 7, Visual Studio 2010, .net framework 4

I try to evaluate RadGridView but with simple file explorer (hierarchy, self reference, unbound mode, load on demand/expansion) and I get exceptions.

 

I isolate problems to simple file explorer. Cound You help me to solve these problems ?

1. Add rows in begin/end section after  expanded event.

Is it necessary to add rows in statements begin/end ?

If I do it, I get exception


System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=Telerik.WinControls
  StackTrace:
       at Telerik.WinControls.RadObject.RaisePropertyNotifications(RadPropertyValue propVal, Object oldValue, Object newValue, ValueSource oldSource)
       at Telerik.WinControls.RadObject.SetValueCore(RadPropertyValue propVal, Object propModifier, Object newValue, ValueSource source)
       at Telerik.WinControls.RadElement.SetValueCore(RadPropertyValue propVal, Object propModifier, Object newValue, ValueSource source)
       at Telerik.WinControls.RadObject.OnTwoWayBoundPropertyChanged(PropertyBinding binding, Object newValue)
       at Telerik.WinControls.PropertyBinding.UpdateSourceProperty(Object newValue)
       at Telerik.WinControls.RadPropertyValue.SetLocalValue(Object value)
       at Telerik.WinControls.RadObject.SetValueCore(RadPropertyValue propVal, Object propModifier, Object newValue, ValueSource source)
       at Telerik.WinControls.RadElement.SetValueCore(RadPropertyValue propVal, Object propModifier, Object newValue, ValueSource source)
       at Telerik.WinControls.UI.GridExpanderItem.set_Expanded(Boolean value)
       at Telerik.WinControls.UI.GridExpanderItem.OnMouseUp(MouseEventArgs e)
       at Telerik.WinControls.RadElement.OnCLREventsRise(RoutedEventArgs args)
       at Telerik.WinControls.RadElement.OnBubbleEvent(RadElement sender, RoutedEventArgs args)
       at Telerik.WinControls.RadItem.OnBubbleEvent(RadElement sender, RoutedEventArgs args)
       at Telerik.WinControls.RadElement.RaiseBubbleEvent(RadElement sender, RoutedEventArgs args)
       at Telerik.WinControls.RadItem.RaiseBubbleEvent(RadElement sender, RoutedEventArgs args)
       at Telerik.WinControls.RadElement.RaiseRoutedEvent(RadElement sender, RoutedEventArgs args)
       at Telerik.WinControls.RadElement.DoMouseUp(MouseEventArgs e)
       at Telerik.WinControls.ComponentInputBehavior.OnMouseUp(MouseEventArgs e)
       at Telerik.WinControls.RadControl.OnMouseUp(MouseEventArgs e)
       at Telerik.WinControls.UI.RadGridView.OnMouseUp(MouseEventArgs e)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at Telerik.WinControls.RadControl.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at TelerikRadControlsWinFormsPrototype.Program.Main() in D:\rdawidziuk\src\OSS 12.2\Support\Prototypes\Technology\Presentation\TelerikRadControlsWinFormsPrototype\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

2. During keyboard manipulate:
    1. enter - expand
    1. selected cell chage with arrow keys

 i get exception. It takes some time, but after minutes I always get this exception:

 

System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=Telerik.WinControls.GridView
  StackTrace:
       at Telerik.WinControls.UI.GridTraverser.StepInHierarchyBackward()
       at Telerik.WinControls.UI.GridTraverser.MovePreviousCore()
       at Telerik.WinControls.UI.GridTraverser.MovePrevious()
       at Telerik.WinControls.UI.BaseGridNavigator.MoveToNextRow(Int32 step, Boolean moveNextDirection)
       at Telerik.WinControls.UI.BaseGridNavigator.SelectPreviousColumn()
       at Telerik.WinControls.UI.GridRowBehavior.ProcessLeftKey(KeyEventArgs keys)
       at Telerik.WinControls.UI.GridRowBehavior.ProcessKey(KeyEventArgs keys)
       at Telerik.WinControls.UI.BaseGridBehavior.ProcessKey(KeyEventArgs keys)
       at Telerik.WinControls.UI.BaseGridBehavior.ProcessKeyDown(KeyEventArgs keys)
       at Telerik.WinControls.UI.RadGridView.OnKeyDown(KeyEventArgs e)
       at System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m)
       at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at Telerik.WinControls.RadControl.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at TelerikRadControlsWinFormsPrototype.Program.Main() in D:\rdawidziuk\src\OSS 12.2\Support\Prototypes\Technology\Presentation\TelerikRadControlsWinFormsPrototype\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

3. After column order change I get strange look  columnorderchange.png

My file explorer code:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;
using System.IO;
 
namespace TelerikRadControlsWinFormsPrototype
{
    public partial class MyFileSystemExplorer : Telerik.WinControls.UI.RadForm
    {
        private int idCounter = 0;
 
        public MyFileSystemExplorer()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            // grid initialize
            this.radGridView1.CellFormatting += new CellFormattingEventHandler(radGridView1_CellFormatting);
            this.radGridView1.ChildViewExpanded += new ChildViewExpandedEventHandler(radGridView1_ChildViewExpanded);
            this.radGridView1.Relations.AddSelfReference(this.radGridView1.MasterTemplate, "ID", "ParentID");
            this.radGridView1.ImageList = this.imageList1;
            this.radGridView1.TableElement.RowHeight = 35;
            // colums
            GridViewDataColumn idCol = new GridViewDecimalColumn();
            idCol.DataType = typeof(int);
            idCol.Name = "ID";
            idCol.ReadOnly = true;
            idCol.IsVisible = false;
            this.radGridView1.Columns.Add(idCol);
 
            GridViewDataColumn parentIdCol = new GridViewDecimalColumn();
            parentIdCol.DataType = typeof(int);
            parentIdCol.Name = "ParentID";
            parentIdCol.ReadOnly = true;
            parentIdCol.IsVisible = false;
            this.radGridView1.Columns.Add(parentIdCol);
 
            GridViewDataColumn nameCol = new GridViewTextBoxColumn();
            nameCol.DataType = typeof(string);
            nameCol.Name = "Name";
            nameCol.HeaderText = "Name";
            nameCol.ReadOnly = true;
            this.radGridView1.Columns.Add(nameCol);
 
            GridViewDataColumn modiffCol = new GridViewTextBoxColumn();
            modiffCol.DataType = typeof(DateTime);
            modiffCol.Name = "Creation";
            modiffCol.HeaderText = "Creation";
            modiffCol.ReadOnly = true;
            this.radGridView1.Columns.Add(modiffCol);
 
            // root rows
            List<FileSystemInfoWrp> drivesInfo = new List<FileSystemInfoWrp>();
            foreach (DriveInfo di in DriveInfo.GetDrives())
            {
                drivesInfo.Add(new FileSystemInfoWrp(this.idCounter++, di.RootDirectory));
            }
            this.Add(null, drivesInfo.ToArray());
        }
 
        void radGridView1_ChildViewExpanded(object sender, ChildViewExpandedEventArgs e)
        {
            if (e.IsExpanded)
            {
                FileSystemInfoWrp parent = (FileSystemInfoWrp)e.ParentRow.Tag;
                // adding in begin/end update section invokes NullReferenceException, why ?
                //this.radGridView1.BeginUpdate();
                try
                {
                    this.Add(parent, this.GetFileSystemElements(parent));
                }
                finally
                {
                    //this.radGridView1.EndUpdate();
                }
                this.radGridView1.GridNavigator.SelectRow(e.ParentRow);
            }
            else
            {
                // remove child nodes, always read files from hdd
                foreach(GridViewRowInfo gvri in e.ParentRow.ChildRows)
                {
                    this.radGridView1.Rows.Remove(gvri);
                }
            }
        }
 
        void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e)
        {
            GridDataCellElement cell = e.CellElement as GridDataCellElement;
            if (cell != null && cell.ExpanderItem != null)
            {
                cell.ImageAlignment = ContentAlignment.MiddleLeft;
                cell.ExpanderItem.Alignment = ContentAlignment.MiddleLeft;
 
                if (((FileSystemInfoWrp)e.Row.Tag).ElementInfo is DirectoryInfo)
                {
                    if (e.Row.IsExpanded)
                    {
                        cell.Image = this.imageList1.Images[1];
                    }
                    else
                        cell.Image = this.imageList1.Images[0];
 
                    cell.ExpanderItem.Visibility = ElementVisibility.Visible;
                }
                else
                {
                    cell.Image = this.imageList1.Images[2];
                    cell.ExpanderItem.Visibility = ElementVisibility.Hidden;
                }
 
                cell.TextImageRelation = TextImageRelation.ImageBeforeText;
            }
        }
 
        private FileSystemInfoWrp[] GetFileSystemElements(FileSystemInfoWrp root)
        {
            List<FileSystemInfoWrp> result = new List<FileSystemInfoWrp>();
 
            if (root.ElementInfo is DirectoryInfo)
            {
                try
                {
                    FileSystemInfo[] infos = ((DirectoryInfo)root.ElementInfo).GetFileSystemInfos();
                    foreach (FileSystemInfo fi in infos)
                    {
                        result.Add(new FileSystemInfoWrp(this.idCounter++, fi));
                    }
                }
                catch // omits io exception
                {
                }
            }
 
            return result.ToArray();
        }
 
        private void Add(FileSystemInfoWrp parent, FileSystemInfoWrp[] fileInfos)
        {
            foreach (FileSystemInfoWrp fsiw in fileInfos)
            {
                GridViewRowInfo row = this.radGridView1.Rows.AddNew();
                row.Cells["ID"].Value = fsiw.Id;
                if (parent != null)
                    row.Cells["ParentID"].Value = parent.Id;
                row.Cells["Name"].Value = fsiw.ElementInfo.Name;
                row.Cells["Creation"].Value = fsiw.ElementInfo.CreationTime;
 
                row.Tag = fsiw;
            }
        }
    }
 
    public class FileSystemInfoWrp
    {
        public int Id { get; set; }
        public FileSystemInfo ElementInfo { get; set; }
 
        public FileSystemInfoWrp(int id, FileSystemInfo elementInfo)
        {
            this.Id = id;
            this.ElementInfo = elementInfo;
        }
    }
}

designer:

using TelerikRadControlsWinFormsPrototype.Properties;
namespace TelerikRadControlsWinFormsPrototype
{
    partial class MyFileSystemExplorer
    {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
 
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
 
            #region Windows Form Designer generated code
 
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.components = new System.ComponentModel.Container();
                System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MyFileSystemExplorer));
                this.radGridView1 = new Telerik.WinControls.UI.RadGridView();
                this.imageList1 = new System.Windows.Forms.ImageList(this.components);
                ((System.ComponentModel.ISupportInitialize)(this.radGridView1)).BeginInit();
                ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
                this.SuspendLayout();
                //
                // radGridView1
                //
                this.radGridView1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(248)))), ((int)(((byte)(248)))), ((int)(((byte)(248)))));
                this.radGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.radGridView1.ForeColor = System.Drawing.Color.Black;
                this.radGridView1.Location = new System.Drawing.Point(0, 0);
                //
                // radGridView1
                //
                this.radGridView1.MasterTemplate.AllowColumnChooser = false;
                this.radGridView1.MasterTemplate.AutoGenerateColumns = false;
                this.radGridView1.MasterTemplate.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill;
                this.radGridView1.MasterTemplate.Caption = null;
                this.radGridView1.MasterTemplate.MultiSelect = true;
                this.radGridView1.MasterTemplate.ShowGroupedColumns = true;
                this.radGridView1.Name = "radGridView1";
                //
                //
                //
                this.radGridView1.RootElement.ForeColor = System.Drawing.Color.Black;
                this.radGridView1.Size = new System.Drawing.Size(1216, 786);
                this.radGridView1.TabIndex = 2;
                this.radGridView1.Text = "radGridView1";
                this.radGridView1.ThemeName = "Telerik";
                //
                // imageList1
                //
                this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
                this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
                this.imageList1.Images.SetKeyName(0, "folder_blue_open1.png");
                this.imageList1.Images.SetKeyName(1, "folder1.png");
                this.imageList1.Images.SetKeyName(2, "new1.png");
                //
                // MyFileSystemExplorer
                //
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(1216, 786);
                this.Controls.Add(this.radGridView1);
                this.Name = "MyFileSystemExplorer";
                //
                //
                //
                this.RootElement.ApplyShapeToControl = true;
                this.Text = "My File System Explorer";
                this.Load += new System.EventHandler(this.Form1_Load);
                ((System.ComponentModel.ISupportInitialize)(this.radGridView1)).EndInit();
                ((System.ComponentModel.ISupportInitialize)(this)).EndInit();
                this.ResumeLayout(false);
 
            }
 
            #endregion
            private Telerik.WinControls.UI.RadGridView radGridView1;
            private System.Windows.Forms.ImageList imageList1;
    }
}

Cound You help me to solve these problems ?

Regards,
Robert

8 Answers, 1 is accepted

Sort by
0
Richard Slade
Top achievements
Rank 2
answered on 14 Feb 2011, 02:58 PM
Hello Robert,

The reason that you are getting the folder images in the other column as well is due to the way the RadGridView uses UI Virtualization. For more information on this link regarding the logical Vs visual structure. The code below is a your method that has been altered to ensure it is only rendering the image for the correct column.

void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e)
{
      
    GridDataCellElement cell = e.CellElement as GridDataCellElement;
    // added in check for column (name=="Name")
    if (cell != null && cell.ExpanderItem != null && cell.ColumnInfo.Name == "Name")
    {
        cell.ImageAlignment = ContentAlignment.MiddleLeft;
        cell.ExpanderItem.Alignment = ContentAlignment.MiddleLeft;
        if (((FileSystemInfoWrp)e.Row.Tag).ElementInfo is DirectoryInfo)
        {
            if (e.Row.IsExpanded)
            {
                cell.Image = this.imageList1.Images[1];
            }
            else
                cell.Image = this.imageList1.Images[0];
            cell.ExpanderItem.Visibility = ElementVisibility.Visible;
        }
        else
        {
            cell.Image = this.imageList1.Images[2];
            cell.ExpanderItem.Visibility = ElementVisibility.Hidden;
        }
        cell.TextImageRelation = TextImageRelation.ImageBeforeText;
    }
}

to answer your other questions, the best thing I can do is point you towards the Telerik Demo that simulates a File Explorer. If you look on your PC, in the Telerik Folder there is a demo. In the demo under Integration >> File Explorer you will find an excellent implementation of a Windows Explorer style form that should point you in the right direction.

Hope that helps
Richard
0
Robert
Top achievements
Rank 1
answered on 14 Feb 2011, 04:36 PM
Hello Richard,

thanks for help, 
problems with column reordering is now solved.

Unfortunatly first exception adding rows in beging/end excetion not, I suppose that without this section I lose on performance.
Is it true ?

I have still problem with NullReferenceException in method Telerik.WinControls.UI.GridTraverser.StepInHierarchyBackward()
described in second point. I have created support ticket 394139 with bug report.

I missed integration branch in Your demo, thank you. I skim the code of Your file explorer but
unfortunaltely File Explorer looks quite diffrent, You use RadTreeView and RadGridView without hierarchy in RadGridView.

I need to build something like tree list view with load on demand on your winforms radgridView, is it possible ?

Regards,
Robert
0
Richard Slade
Top achievements
Rank 2
answered on 14 Feb 2011, 04:54 PM
Hello Robert,

The RadGridView can do Load On Demand using the RowSourceNeeded event and giving a child template a HierarchyDataProvider. There is some documentation on this which you can find here. You may also find this link on binding to hierarcical data useful too.
Regards,
Richard
0
Robert
Top achievements
Rank 1
answered on 14 Feb 2011, 08:12 PM
Hello Richard,

Unfortunatly this is not what I want to achieve. Documentation which you provide alows to create hierarchy with child templates, so i get more than one header row. Our systems mostly presents data in listview or treelistview. I have a hope that tree list view can be done with self-reference hierarchy , but unfortunatly  exceptions occurs and now I can not recomend this component for use in my company.

Kind Regards,
Robert Dawidziuk
0
Richard Slade
Top achievements
Rank 2
answered on 14 Feb 2011, 11:21 PM
Hello Robert.

On Master and Child Templates, Column Headers can be hidden by using (for exmaple)
this.radGridView1.MasterTemplate.Templates[0].AllowAddNewRow = false;

For Self Referencing radGridViews, you need to provide a datasource that self references. Here is a full exmaple that was taken from the documentation at: this link

Designer File
namespace RadGridView_SelfReferenceFolder_CS
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components;
  
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
  
        #region Windows Form Designer generated code
  
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.radGridView1 = new Telerik.WinControls.UI.RadGridView();
            ((System.ComponentModel.ISupportInitialize)(this.radGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // radGridView1
            // 
            this.radGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.radGridView1.Location = new System.Drawing.Point(0, 0);
            this.radGridView1.Name = "radGridView1";
            this.radGridView1.Size = new System.Drawing.Size(377, 431);
            this.radGridView1.TabIndex = 0;
            this.radGridView1.Text = "radGridView1";
            this.radGridView1.CellFormatting += new Telerik.WinControls.UI.CellFormattingEventHandler(this.radGridView1_CellFormatting);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(377, 431);
            this.Controls.Add(this.radGridView1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.radGridView1)).EndInit();
            this.ResumeLayout(false);
  
        }
  
        #endregion
  
        private Telerik.WinControls.UI.RadGridView radGridView1;
    }
}

Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Telerik.WinControls.UI;
  
namespace RadGridView_SelfReferenceFolder_CS
{
    public partial class Form1 : Form
    {
        // replace with your own resource images
        Image documentImage = Properties.Resources.document;
        Image folderImage = Properties.Resources.folder;
        BindingList<FileSystemItem> list = new BindingList<FileSystemItem>();
        int fileFolderIndex = 0;
  
        public Form1()
        {
            InitializeComponent();
        }
  
        private void Form1_Load(object sender, EventArgs e)
        {
            GetFilesAndFolders(@"C:\Program Files", 0);
            this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
  
            this.radGridView1.Relations.AddSelfReference(this.radGridView1.MasterTemplate, "Id", "ParentFolderId");
            this.radGridView1.DataSource = list;
  
            this.radGridView1.Columns["Id"].IsVisible = false;
            this.radGridView1.Columns["ParentFolderId"].IsVisible = false;
            this.radGridView1.Columns["FileSystemInfoType"].IsVisible = false;
        }
  
  
  
        public void GetFilesAndFolders(string dir, int parentId)
        {
            DirectoryInfo di = new DirectoryInfo(dir);
            FileInfo[] rgFiles = di.GetFiles();
            foreach (FileInfo fi in rgFiles)
            {
                fileFolderIndex++;
                list.Add(new FileSystemItem(fileFolderIndex, "File", fi.Name, fi.CreationTime, parentId));
            }
  
            DirectoryInfo[] dirs = di.GetDirectories();
            foreach (DirectoryInfo d in dirs)
            {
                fileFolderIndex++;
                list.Add(new FileSystemItem(fileFolderIndex, "Folder", d.Name, d.CreationTime, parentId));
                GetFilesAndFolders(d.FullName, fileFolderIndex);
            }
        }
  
        void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)
        {
            GridDataCellElement dataCell = e.CellElement as GridDataCellElement;
  
            if (dataCell.ColumnInfo.Name == "Name")
            {
                GridViewDataRowInfo dataRow = dataCell.RowInfo as GridViewDataRowInfo;
                if (dataRow != null)
                {
                    dataCell.ImageAlignment = ContentAlignment.MiddleLeft;
  
                    string valueType = Convert.ToString(dataRow.Cells["FileSystemInfoType"].Value).ToUpperInvariant();
  
                    if (valueType.Contains("FILE"))
                    {
                        dataCell.Image = documentImage;
                    }
                    else
                    {
                        dataCell.Image = folderImage;
                    }
  
                    dataCell.TextImageRelation = TextImageRelation.ImageBeforeText;
                }
            }
            else
            {
                dataCell.ResetValue(LightVisualElement.ImageProperty, Telerik.WinControls.ValueResetFlags.Local);
                dataCell.ResetValue(LightVisualElement.ImageAlignmentProperty, Telerik.WinControls.ValueResetFlags.Local);
                dataCell.ResetValue(LightVisualElement.TextImageRelationProperty, Telerik.WinControls.ValueResetFlags.Local);
                dataCell.ResetValue(LightVisualElement.ImageLayoutProperty, Telerik.WinControls.ValueResetFlags.Local);
            }
        }
  
  
    }
  
    public class FileSystemItem
    {
        int id;
        string name;
        DateTime creationTime;
        int parentFolderId;
        private string type;
  
        public int Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }
  
        public string FileSystemInfoType
        {
            get
            {
                return type;
            }
            set
            {
                type = value;
            }
        }
  
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
  
        public DateTime CreationTime
        {
            get
            {
                return creationTime;
            }
            set
            {
                creationTime = value;
            }
        }
  
        public int ParentFolderId
        {
            get
            {
                return parentFolderId;
            }
            set
            {
                parentFolderId = value;
            }
        }
  
        public FileSystemItem(int id, string type, string name, DateTime creationTime, int parentFolderId)
        {
            this.id = id;
            this.type = type;
            this.name = name;
            this.creationTime = creationTime;
            this.parentFolderId = parentFolderId;
        }
    }
}

Load on demand RadGridViews, dictate that you need to provide one or more child templates, and then handle the RowSourceNeeded event as shown in this link

Hope that helps explain the differences but if you need more informartion, please let me know
Regards,
Richard
0
Richard Slade
Top achievements
Rank 2
answered on 15 Feb 2011, 02:38 PM
Hi Robert,

How did this go?
In addition, I thought you might be interested in Telerik's reply in this forum post regarding future plans for self reference + load on demand.
Hope that helps
Richard
0
Robert
Top achievements
Rank 1
answered on 15 Feb 2011, 03:44 PM
Hello Richard,

your last post is helpful,
in post is clearly written that self - reference and load on demand is not supported.

I hope that in next releases will be work better.

thanks for information, 
now it is clear that using self-reference require data source fully filled
and load on demand requires child templates.

unfortunatly in many cases I need to load data from database after row expansion and use only master template.

Thanks for help,
Robert 
0
Richard Slade
Top achievements
Rank 2
answered on 15 Feb 2011, 03:54 PM
You're welcome Robert. Please remember to mark helpful posts as answer and if you need any further information, just let me know
regards,
Richard
Tags
GridView
Asked by
Robert
Top achievements
Rank 1
Answers by
Richard Slade
Top achievements
Rank 2
Robert
Top achievements
Rank 1
Share this question
or