2017-03-08 76 views
0

的性质我有一个GridView获取值了一个对象移到另一个类

INSEE1 Commune 
------ ------- 
10002 AILLEVILLE 
10003 BRUN 

我有一个返回对象列表的脚本。

List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1"); 

我的Temp是我选择的INSSE1的对象列表。

,但现在我加入公社还,所以我的脚本成为:

List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune"); 

,我的温度是INSEE1和公社看图像的对象的列表:

enter image description here

我怎么能acces 10002和AILLEVILLE?

我已经尝试用投我Pers_INSEE类的吧:

public class Pers_InseeZone 
{ 
    string _Code_Insee; 
    public string Code_Insee 
    { 
     get { return _Code_Insee; } 
     set { _Code_Insee = value; } 
    } 

    string _Commune; 
    public string Commune 
    { 
     get { return _Commune; } 
     set { _Commune = value; } 
    } 
} 

foreach (var oItem in Temp) 
       { 
Pers_InseeZone o = (Pers_InseeZone)oItem; 

} 

,但我不行,我不能投了。 我已经试过这样:

foreach (var oItem in Temp) 
{ 
    var myTempArray = oItem as IEnumerable; 

    foreach (var oItem2 in myTempArray) 
    { 
     string res= oItem2.ToString(); 

....

res = 10002的价值,但我怎么能得到AILEVILLE的价值?

Temp[0].GetType();值是:提前

enter image description here

感谢

+0

能你用'typeof'来访问'object'的具体类是什么?然后投射到对象中 – Turbot

+1

您将获得数组数组。只需使用索引来阅读第二个:'oItem [1]'。 – Sinatr

+0

你可以请'Temp [0] .GetType()'并发布结果吗? –

回答

1

好吧我认为是这样的,所以如前所述,在每个对象内部都有一个对象数组,因此您需要先将列表中的每个对象都转换为对象数组:object[]然后您可以访问每个部分。这里是再现你的问题的例子:

object[] array = new object[] {10002, "AILEEVILLE"};  
List<object> Temp = new List<object> {array}; 

enter image description here

而且该解决方案:

// cast here so that the compiler knows that it can be indexed 
object [] obj_array = Temp[0] as object[]; 

List<Pers_InseeZone> persList = new List<Pers_InseeZone>(); 

Pers_InseeZone p = new Pers_InseeZone() 
{ 
    Code_Insee = obj_array[0].ToString(), 
    Commune = obj_array[1].ToString() 
}; 

persList.Add(p); 

应用到你的代码,它会是这个样子:

List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune"); 
List<Pers_InseeZone> persList = new List<Pers_InseeZone>(); 

foreach (object oItem in Temp) 
{ 
    object [] obj_array = oItem as object[]; 

    Pers_InseeZone p = new Pers_InseeZone() 
    { 
     Code_Insee = obj_array[0].ToString(), 
     Commune = obj_array[1].ToString() 
    }; 

    persList.Add(p); 
} 
+0

谢谢你的作品....... –

0

的问题是下降的事实你class不匹配相同的结构,你所得到的数据,所以它不能被投入它。

相反,为什么不迭代结果并构建类的新实例?

var tempList = new List<Pers_InseeZone>(); 
foreach (var oItem in Temp) 
{ 
    tempList.Add(new Pers_InseeZone(oItem[0], oItem[1])); 
} 

您将需要添加一个构造函数到你的Pers_InseeZone类,并在那里分配变量。

+0

谢谢,但我不能索引oItem,因为是一个对象。 –

相关问题