C# 在c中创建动态属性并绑定哈希表

C# 在c中创建动态属性并绑定哈希表,c#,C#,我试图将行绑定到gridview,它不仅包含Category表的字段,还包含其他表的字段。所以我为所有这些字段设置了属性。但是由于表中的列可能会频繁更改,因此我还需要动态更改属性。我发现了以下一种使用哈希表的方法。但我无法将哈希表值绑定到gridview 如何更好地解决这个问题 public partial class Form1 : Form { public class Row { // properties public Hashtable

我试图将行绑定到gridview,它不仅包含Category表的字段,还包含其他表的字段。所以我为所有这些字段设置了属性。但是由于表中的列可能会频繁更改,因此我还需要动态更改属性。我发现了以下一种使用哈希表的方法。但我无法将哈希表值绑定到gridview

如何更好地解决这个问题

public partial class Form1 : Form
{
    public class Row
    {
        // properties
        public Hashtable Properties = new Hashtable();


    }
    public Form1()
    {
        InitializeComponent();
        DataClasses1DataContext context = new DataClasses1DataContext();
        var st = from c in context.Categories
                 select c;
        var p = from pr in context.Products
                 select p;

        Row r = new Row();
        //List<Row> listrow = new List<Row>();
        foreach (var item in st)
        {
            r.Properties.Add(item.Description, item.Description);
        }

        this.gridControl1.DataSource = r.Properties.Values;
    }
}
Values是一个ICollection,但需要IList来绑定数据。理想情况下,您确实需要一个键入的列表。为什么在这里使用哈希表?我怀疑你有足够的行需要它

相反,请使用类型化列表或BindingList。请注意,您只能绑定到网格中的单个类型。我一点也不清楚您希望在网格中显示什么,因为目前您只添加了描述,但在最简单的级别:

this.gridControl1.DataSource = context.Categories.ToList();
或者更好:

this.gridControl1.DataSource = context.Categories.ToBindingList();
这不会帮助您将产品和类别放在一个网格中。。。但是,如果它们不是同一类型的话,什么也不会发生。一个可能有效的方法是匿名类型的公共属性:

var query = (from c in context.Categories
             select new {Id = c.CategoryId, Name = c.Category,
                   Description = c.Description }).Concat(
             from p in context.Products
             select new {Id = p.ProductId, Name = p.Product,
                   Description = p.ProductDescription });

this.gridControl1.DataSource = query.ToList();
但是,请注意,匿名类型是不可变的,不可编辑,因此使用ToBindingList没有任何意义。另一个选项是为此目的声明自己的类,这意味着它也可以编辑。

Hashtable.Values是一个ICollection,但需要IList来绑定数据。理想情况下,您确实需要一个键入的列表。为什么在这里使用哈希表?我怀疑你有足够的行需要它

相反,请使用类型化列表或BindingList。请注意,您只能绑定到网格中的单个类型。我一点也不清楚您希望在网格中显示什么,因为目前您只添加了描述,但在最简单的级别:

this.gridControl1.DataSource = context.Categories.ToList();
或者更好:

this.gridControl1.DataSource = context.Categories.ToBindingList();
这不会帮助您将产品和类别放在一个网格中。。。但是,如果它们不是同一类型的话,什么也不会发生。一个可能有效的方法是匿名类型的公共属性:

var query = (from c in context.Categories
             select new {Id = c.CategoryId, Name = c.Category,
                   Description = c.Description }).Concat(
             from p in context.Products
             select new {Id = p.ProductId, Name = p.Product,
                   Description = p.ProductDescription });

this.gridControl1.DataSource = query.ToList();
但是,请注意,匿名类型是不可变的,不可编辑,因此使用ToBindingList没有任何意义。另一个选项是为此声明自己的类,这意味着它也可以编辑