我有一个像这样的数据库类
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; }
}
DataGridView使用BindingList作为它的数据源,我将gridview的选定行检索为数据库类实例,如下所示:
Database currentObject = (Database)dataGridView1.CurrentRow.DataBoundItem;
现在我试图遍历" currentObject"的属性。像这样:
foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{
var name = property.Name;
object obj = property.GetValue(this, null);
}
但是在object obj = property.GetValue(this, null);
行上它崩溃了,我得到了:
未处理的类型' System.Reflection.TargetException' 发生在mscorlib.dll
其他信息:对象与目标类型不匹配。
我在这里缺少什么?
答案 0 :(得分:17)
您必须从
更改此行 object obj = property.GetValue(this, null);
到
object obj = property.GetValue(currentObject, null);
GetValue
的第一个参数需要目标实例来获取值。所以当你说this
运行时抛出异常,说this
中没有这样的属性。
答案 1 :(得分:5)
试试这个
foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{
var name = property.Name;
object obj = property.GetValue(currentObject, null);
}