Binding a custom list property to a DatagridView

I have a problem that is hard to explain. Essentially, I have a list of a specific class that we can call MyObj. One of the properties of this object is its own list. I would like to bind this list to dataGridView and get this specific property, which also appears in the list. Any ideas? Am I clear enough? :-P ..

Here is an idea. I have my own custom list object overriding the ToString () method:

public class CategoriesList : List<Category> { public override string ToString() {...} } 

This is used as a property in the object, for example:

 public MyObj { public string Property1 {get; set; } public string Property2 {get; set; } public CategoriesList Categories {get; set; } } 

In turn, I have a list of these objects, for example:

 List<MyObj> myDataSouce = SomeRepository.GetMyObjList(); 

Where I bind this to a datagrid view:

 MyDataGridView.DataSource = myDataSource; 

Property1 and Property2 are automatically generated. Is there a way to add a CategoriesList property? Earlier, I thought that overriding the ToString () method for the class would be enough.

I really got lost on this, since I have no idea how even google for it: -P

+4
source share
2 answers

Assuming you want to display a specific value instead of a list in a datagridview, you will want to use your own TypeConverter. Otherwise, you will need to place the control in a datagridview column that supports lists, such as a drop-down list and a binding to it.

For the first:

In principle, decorate a category property with a special type:

 [TypeConverter(typeof(MyConverter))] public CategoriesList Categories { get; set; } 

Then use a custom type converter, which basically tells the datagrid that when it encounters the category property that appears on the display:

 public class MyConverter : TypeConverter { public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is CategoriesList) { return value.ToString(); } return base.ConvertFrom(context, culture, value); } } 

You will need to add your column manually to bind the data by adding an unbound column and specifying the name DataPropertyName to map the property to this column, in this case "Categories"

If you want to display the properties of the second level, this can help: http://blogs.msdn.com/b/msdnts/archive/2007/01/19/how-to-bind-a-datagridview-column-to-a- second-level-property-of-a-data-source.aspx

+3
source

Source: https://habr.com/ru/post/1347071/


All Articles