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.
}
4

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.