0

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.

Austin
  • 3,010
  • 23
  • 62
  • 97
  • Is this winforms, wpf, webforms, mvc, android, ios, windows phone? Need this information – Joe May 09 '14 at 16:24
  • @Joe dumb question, I am not entirely sure I selected WPF or WinForm. does this, imply a winform? using System.Windows.Forms; – Austin May 09 '14 at 16:28
  • I would've thought so, but do you have any XAML files in your project? – Joe May 09 '14 at 16:30
  • No. I am using the drag drop feature for my form (like netbeans). but I have named my variables and such. Does this matter though if I am just need to pull out the variable data? I know how to populate the combobox already. – Austin May 09 '14 at 16:31
  • 1
    If you were using WPF, you can do some nice things with the bindings on the UI (where this logic belongs), but sounds like winforms so this won't apply – Joe May 09 '14 at 16:33

2 Answers2

2
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();
rwisch45
  • 3,692
  • 2
  • 25
  • 36
0

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();
Community
  • 1
  • 1
Sector95
  • 641
  • 6
  • 12