2014-04-24 52 views
1

我正在循环一个具有多个属性的类,并且正在搜索具有相同ID的任何文本框。如果有一个匹配,那么我想更新的属性值,该文本框的值,但我收到此错误:反射返回对象中的SetValue与目标类型不匹配

Object does not match target type

这是代码:

foreach (var prop in contactInfo.GetType().GetProperties())      
{       
    var ctrl = WizardCampaign.FindControl(prop.Name) ?? Page.Master.FindControl(prop.Name);   

    if (ctrl != null) 
    { 
     if (ctrl.GetType() == typeof(TextBox)) 
     { 
      var r = (TextBox)ctrl;                                                
      prop.SetValue(prop, r.Text, null);         
     } 
    } 
} 
+0

而不是'如果(CTRL!= NULL)'和'如果(ctrl.GetType()== typeof运算(文本框))'你可以将它们结合起来,包括派生的对象从文本框使用'if(ctrl是TextBox)' – Silvermind

回答

5

看看这里:

prop.SetValue(prop, r.Text, null); 

SetValue应该把你想要改变作为第一个参数的对象,但你传递PropertyInfo对象。我相信你的实际代码应该是:

prop.SetValue(contactInfo, r.Text, null); 
+0

当然 - 谢谢 – okenshield

相关问题