0

I need make a properties dynamically. because I need bind to DataGrid.

I made a simple class, but I have no more ideas.

public class MyDataModel {
    public int Id {get; set;}
    public string Name {get; set;}
    public bool CheckItem1 {get; set;}
    public bool CheckItem2 {get; set;}
    public bool CheckItem3{get; set;}
    ....
    public bool CheckItenN {get; set;}
}

var checkList = GetCheckItems();
foreach(var item in checkList){
    //I want to add item's property to MyDataModel.
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179

3 Answers3

2

While this doesn't answer the question I think your actual problem may be solved by binding to a DataTable instead.

The below code creates dynamic columns and rows to a new DataTable;

DataTable datatable = new DataTable(); 
datatable.Columns.Add("Col1");
datatable.Columns.Add("Col2");

DataRow row = datatable.NewRow();
row["Col1"] = "One";
row["Col2"] = "Two";
datatable.Rows.Add(row);

Bind to the result.

DaggeJ
  • 2,094
  • 1
  • 10
  • 22
0

So, In theory, you can dynamicaly create new class that extends the current and add new proppery. And then use it with dynamic keyword.

But this is not trivial and it will be very slow. C# is not a scrypt language. And thets why you should write most of this things.

So, you can create property and it will equals null in cases when you not need this property. But in other cases you will setup this property and use it.

TemaTre
  • 1,422
  • 2
  • 12
  • 20
0

I agree with @TemaTre, creating classes dynamically is possible, but it is not the encouraged way to solve this kind of problems.

Creating "properties" variables might be a solution, but they quickly will clutter your code.

There are alternatives, though. You can bind the DataGrid to a dictionary (Binding a Dictionary to the DataGridView in C#?) or an list of lists (https://stackoverflow.com/a/22928980/4628597).

These ways are more powerful, more easily extendible and easier to maintain.

Alvin Sartor
  • 2,249
  • 4
  • 20
  • 36