Reputation: 4492
I have a list of StudentViewModel
object. I am binding this list with a DataGridView, and the column generatation is set to automatic according to the bound model's properties.
public async Task LoadGridView()
{
Tuple<List<StudentViewModel>, int> result = await App.StudentService.SearchAsync(studentRequestModel);
dataGridView1.DataSource = null;
dataGridView1.DataSource = result.Item1;
}
In the StudentViewModel, I have decorated some of the properties with a custom attribute IsViewable
.
[AttributeUsage(AttributeTargets.Property)]
public class IsViewable: Attribute
{
public bool Value { get; set; }
}
usage:
[IsViewable(Value = true)]
public string Name { get; set; }
Idea is, just before binding with the UI Control, I want to filter the list and make a new list of anonymous object so that my grid will be populated with only selected properties.
Note: I don't want to create separate view models specific to Grids. I will refactor it if it creates performance issues.
Upvotes: 1
Views: 3143
Reputation: 4492
The catch is, I serialized the dynamic list and then deserialized. Then I bind that dynamic list with the datagridview and it worked like a charm.
The whole project can be found here foyzulkarim/GenericComponents
Caller / Usage:
Type type = typeof(StudentViewModel);
PropertyInfo[] properties = type.GetProperties();
var infos = properties.Where(x => x.CustomAttributes.Any(y => y.AttributeType == typeof(IsViewable))).ToList();
List<StudentViewModel> models = result.Item1;
List<dynamic> list = models.Select(x => GetValue(x, infos)).ToList();
string serializeObject = JsonConvert.SerializeObject(list);
var deserializeObject = JsonConvert.DeserializeObject<List<dynamic>>(serializeObject);
dataGridView1.DataSource = deserializeObject;
Upvotes: 1