Dim*_*imo 9 c# sql database winforms
我有这样的数据库类
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; }
}
Run Code Online (Sandbox Code Playgroud)
DataGridView使用BindingList作为它的数据源,我将gridview的选定行检索为数据库类实例,如下所示:
Database currentObject = (Database)dataGridView1.CurrentRow.DataBoundItem;
Run Code Online (Sandbox Code Playgroud)
现在我试图循环遍历"currentObject"的属性,如下所示:
foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{
var name = property.Name;
object obj = property.GetValue(this, null);
}
Run Code Online (Sandbox Code Playgroud)
但在线object obj = property.GetValue(this, null);它崩溃了,我得到:
mscorlib.dll中出现未处理的"System.Reflection.TargetException"类型异常
附加信息:对象与目标类型不匹配.
我在这里错过了什么?
Sri*_*vel 18
你必须改变这一行
object obj = property.GetValue(this, null);
Run Code Online (Sandbox Code Playgroud)
至
object obj = property.GetValue(currentObject, null);
Run Code Online (Sandbox Code Playgroud)
第一个参数GetValue需要目标实例来获取值.所以当你说this运行时抛出异常,说没有这样的属性this.
试试这个
foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{
var name = property.Name;
object obj = property.GetValue(currentObject, null);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13701 次 |
| 最近记录: |