I have a database class like this
class Database
{
[Browsable(false)]
public long Session { get; set; }
public string Förnamn { get; set; }
public string Efternamn { get; set; }
public string Mail { get; set; }
}
A DataGridView uses BindingList as it's datasource and I retrieve the selected row of a gridview as a database class instance like this:
Database currentObject = (Database)dataGridView1.CurrentRow.DataBoundItem;
Now I'm trying to loop through the properties of "currentObject" like this:
foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{
var name = property.Name;
object obj = property.GetValue(this, null);
}
But on line object obj = property.GetValue(this, null); it crashes and I get:
An unhandled exception of type 'System.Reflection.TargetException' occurred in mscorlib.dll
Additional information: Object does not match target type.
What am I missing here?
When overridden in a derived class, returns the property value of a specified object that has the specified binding, index, and culture-specific information. Returns the property value of a specified object. public object? GetValue (object? obj); The object whose property value will be returned. The property value of the specified object.
Returns the property value of a specified object with optional index values for indexed properties. When overridden in a derived class, returns the property value of a specified object that has the specified binding, index, and culture-specific information. Returns the property value of a specified object. public object? GetValue (object? obj);
jQuery Uncaught TypeError: Cannot read property 'text' of null 2 Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined (using wysiwyg)
You'll have to change this line from
object obj = property.GetValue(this, null);
to
object obj = property.GetValue(currentObject, null);
First parameter of GetValue requires target instance to get the value. so when you say this runtime throws exception saying that no such property exist in this.
Try this
foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{
var name = property.Name;
object obj = property.GetValue(currentObject, null);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With