2011-03-02 45 views
0

我有這樣的代碼列表<Entity>問題

foreach(GridViewRow row in gvTagDeductionList.Rows) 
{ 
    DeductionEntity de = new DeductionEntity(); 

    //modify this condition, make cell number to be more dynamic 
    if (((CheckBox)row.Cells[2].FindControl("chkInclude")).Checked == true) 
    { 
     //following id's are said to be in numeric format in the first place 
     //ede.EmployeeID = Convert.ToInt32(HttpContext.Current.Session["_newEmpID"].ToString()); 
     ede.DeductionID = Convert.ToInt32((((Label)row.Cells[0].FindControl("lblID")).Text).ToString()); 
     ede.CreatedBy_UserID = Convert.ToInt32(HttpContext.Current.Session["_employeeID"].ToString()); 
     ede.UpdatedBy_UserID = Convert.ToInt32(HttpContext.Current.Session["_employeeID"].ToString()); 
     de = e201u.GetDeductionDetails(ede.DeductionID); 
     e201u.InsertEmployeeDeduction(ede); 
     lstEntity.Add(de); 
    } 
} 

de = e201u.GetDeductionDetails(ede.DeductionID); 

內環路這段代碼的第二次相遇後,在這段代碼lstEntity.Add(de);第一個記錄將被改變,最後我會在最後兩在我的最後一個實體列表中獲得條目de = e201u.GetDeductionDetails(ede.DeductionID);

+0

如果您正在將所有內容分配給'e201u.GetDeductionDetails' – Marlon 2011-03-02 06:46:06

+0

您不需要創建一個新的DeductionEntity應該使用事件,而不是每次發生事件時遍歷整個數據網格。只是我2美分。 – leppie 2011-03-02 07:20:37

回答

3

在循環內部,您必須創建您再次插入到列表中的對象。現在您只需插入它,然後更改並再次插入它。您只能將對象的引用保存到列表中,而不是實際的對象本身。作爲你的循環的第一行(你還沒有顯示),請根據對象ede的類型嘗試編寫ede = new ...()

對於所有基於引用的類型(類),將出現相同的「問題」,但不會出現基於值的類型(結構),因爲對於結構,您將對象的實際副本保存到列表中,而不僅僅是像你爲一個班級做的參考。

這裏是一個例子。

public class A 
{ 
    public int Test{ get; set; } 
} 

在代碼中的一些其他地方:

List<A> list = new List<A>(); 
A a = new A(); 
for(int i = 0; i < 2; i++) 
{ 
    a.Test = i; 
    list.Add(a); 
} 

這將結束與包含相同的一個目的兩個引用的列表。所以列表[0]。測試是1,和列表[1]。測試是1

在代碼中的一些其他地方:

List<A> list = new List<A>(); 
for(int i = 0; i < 2; i++) 
{ 
    A a = new A(); 
    a.Test = i; 
    list.Add(a); 
} 

這將結束與一個包含兩個不同的參考名單一個對象。因此,列表[0] .Test爲0,列表[1] .Test爲1.

+0

哦,我明白了..謝謝你的回覆,我現在就試試 – user596583 2011-03-02 06:48:06