2017-03-08 80 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,因爲是一個對象。 –

相關問題