سؤال

I am using a WinForm or WPF (I believe)

I have a List<Student> formStudents = new List<Student>(); Student itself, is an Object, and I am trying to populate a combox with all the "types" or "variables" that my Object Student has.

new Student() { StudentName = "James", Age = 25, Score = 57 };

For this example above, I would try to populate my WinForm ComboBox with values (StudentName, Age, and Score - that I then will search by for results), how can I retrieve those properties from my Object, while it is in a List?

I have tried messing around with IntelliSense (guess and check) but I have had no luck so far.

EDIT: Just for reference, I am only showing part of the code, but my Student Objects are all already populated within the List. I have checked with a .Count on studentForms. I just need to pull out the variables/types.

هل كانت مفيدة؟

المحلول

using System.Reflection;  

var propertyInfos = typeof(Student).GetProperties();
var propnames = new List<string>();

foreach(var prop in propertyInfos){
    propnames.Add(prop.Name)
}

Then bind the propnames list of strings to your combobox.

Using LINQ:

using System.Linq;
using System.Reflection;

var propertyInfos = typeof(Student).GetProperties();
var propnames = propertyInfos.Select(prop => prop.Name).ToList();

نصائح أخرى

This should be helpful: C# Dynamically Get Variable Names and Values in a Class

In the case above, he's passing the results into a dictionary.

http://msdn.microsoft.com/en-us/library/ch9714z3%28v=vs.110%29.aspx

In the example here, they are pushing the names of the fields into an array.

FieldInfo[] myField = myType.GetFields();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top