Иерархические данные с использованием пользовательских объектов (telerik RadGridView) - PullRequest
2 голосов
/ 17 февраля 2011

Предположим, у меня есть

class Person
{
    public int Id {get;set;}
    public string Name {get;set;}
    public List<Person> All {get;set;}

    public Person()
    {
    }

    public List<Person> GetAll()
    {
        //fills the list with person and returns
    }
}

и что у меня есть:

class Address 
{
    public int PersonId {get;set;}
    public string theAddress {get;set;}
    public List<Address> All {get;set;}

    //constructor, etc

    public List<Address> GetAll()
    {
        //fills the address list and returns
    }
}

Что я пытаюсь сделать, это в точности следующее:

//filling the maintemplate with data
radGridView1.DataMember = "Person";
radGridView1.DataSource = new Person().GetAll();     

//address template, the child one
GridViewTemplate template = new GridViewTemplate();
template.DataSource = new Address().GetAll();
template.DataMember = "Address";
radGridView1.MasterTemplate.Templates.Add(template);

//now the relation between those 2 classes

GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate);
relation.ChildTemplate = template;
relation.RelationName = "PersonAddress"; //just a name
relation.ParentColumnNames.Add("Id"); //field to be "joined" to create the relation
relation.ChildColumnNames.Add("PersonId"); //same as above
radGridView1.Relations.Add(relation);

и чтоя получаю именно сетку со знаком «+» рядом с каждым человеком. Проблема в том, что «дочерняя» сетка пуста, и если я пытаюсь добавить данные (по умолчанию это разрешено с пустым конструктором вкласс) я бросаю NullArgumentException

Есть идеи?Я почти сдаюсь.Моя проблема: я использую пользовательские объекты во всех проектах, это не так, как "вы используете наборы данных, оно готово к использованию и т. Д.", Я знаю это, но я хотел бы знать, есть ли способ использовать ПОЛЬЗОВАТЕЛЬСКИЕ ОБЪЕКТЫ или если я готови должны попробовать наборы данных ...

Спасибо, ребята

Ответы [ 2 ]

4 голосов
/ 17 февраля 2011

Похоже, вы используете реализацию WinForms. Если это правильно, то это работает для меня нормально. Пожалуйста, попробуйте

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 Telerik.WinControls.UI;

namespace RadGridView_Hierarchy_CS
{
    public partial class Form1 : Form
    {

        private List<Person> people = new List<Person>();
        private List<Address> addresses = new List<Address>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FillPeople();
            FillAddresses();

            radGridView1.DataSource = people;

            GridViewTemplate template = new GridViewTemplate();
            template.DataSource = addresses;
            radGridView1.MasterTemplate.Templates.Add(template);

            GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate);
            relation.ChildTemplate = template;
            relation.RelationName = "PersonAddress";
            relation.ParentColumnNames.Add("Id");
            relation.ChildColumnNames.Add("PersonId");
            radGridView1.Relations.Add(relation);

        }

        private void FillPeople()
        {
            Person richard = new Person();
            richard.Name = "Richard";
            richard.Id = 1;
            people.Add(richard);
            Person bob = new Person();
            bob.Name = "Bob";
            bob.Id = 2;
            people.Add(richard);
            Person mike = new Person();
            mike.Name = "Mike";
            mike.Id = 3;
            people.Add(mike);
        }

        private void FillAddresses()
        {
            Address house1 = new Address();
            house1.PersonId = 1;
            house1.Id = 1;
            house1.theAddress = "1 The Mews";
            addresses.Add(house1);
            Address house2 = new Address();
            house2.PersonId = 2;
            house2.Id = 2;
            house2.theAddress = "2 The Mews";
            addresses.Add(house2);
        }    
    }

    class Person 
    {     
        public int Id {get;set;}     
        public string Name {get;set;}     


        public Person()     
        { 
        }              
    }

    class Address  
    {
        public int Id { get; set; }   
        public int PersonId {get;set;}    
        public string theAddress {get;set;}     

        public Address()
        { 
        }
    }
}
2 голосов
/ 16 декабря 2011

наткнулся на ваше сообщение при поиске решения для этого, поэтому я буду добавлять мое решение на тот случай, если кому-то оно понадобится ... (используется версия Q1 2011).

в каком-то методе инициализации вашего UC / GridВы можете сделать что-то вроде

     //setup the template 
     GridViewTemplate subtemplate = new GridViewTemplate();
     subtemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
     subtemplate.EnableFiltering = false;
     subtemplate.EnableGrouping = false;
     subtemplate.AutoGenerateColumns = false;

     //define / add the cols
     GridViewTextBoxColumn atextcol = new GridViewTextBoxColumn("Name");
     //further properties of atextcol

      //add the cols to the template
      subtemplate.Columns.Add(atextcol);

      //add the template to the grid
      thegrid.Templates.Add(subtemplate);

     //add a HierarchyDataProvider && subscribe to the RowSourceNeeded-Event
      subtemplate.HierarchyDataProvider = new GridViewEventDataProvider(subtemplate);

      thegrid.RowSourceNeeded += new GridViewRowSourceNeededEventHandler(thegrid_RowSourceNeeded);

, затем в обработчике событий заполните строку / строки

protected void thegrid_RowSourceNeeded(object sender, GridViewRowSourceNeededEventArgs e)
        {
            e.Template.Rows.Clear();
            patentdata cparent = e.ParentRow.DataBoundItem as patentdata;

            foreach (subdataobject sub in parentdata.subs)
            {
                GridViewRowInfo row = e.Template.Rows.NewRow();
                row.Tag = sub;
                row.Cells["Name"].Value = sub.Name;
                e.SourceCollection.Add(row);
            }
        }

так, чтобы это было так.критики?

...