Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

property.GetValue(this, null) leads to "Object does not match target type"

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?

like image 859
Dimo Avatar asked Nov 05 '13 13:11

Dimo


People also ask

What does getValue return when overridden in a derived class?

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.

What is the use of getValue () method?

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);

What are some examples of uncaught type errors in jQuery?

jQuery Uncaught TypeError: Cannot read property 'text' of null 2 Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined (using wysiwyg)


2 Answers

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.

like image 93
Sriram Sakthivel Avatar answered Oct 15 '22 18:10

Sriram Sakthivel


Try this

foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{         
    var name = property.Name;
    object obj = property.GetValue(currentObject, null);    
}
like image 31
Matthew Layton Avatar answered Oct 15 '22 19:10

Matthew Layton