2011-08-17 31 views
0

我不知道如何更新通用列表中的項目後,審查所有發佈在這裏的問題,我很抱歉。這裏是我的問題:使用C#更新一個通用的列表項目

我有這樣的結構:

List<LineInfo> Lines = new List<LineInfo>(); 
    LineInfo LInfo; 
    struct LineInfo 
    { 
     public int line; 
     public int WO; 
     public string Brand; 
     public string Model; 
     public string Customer; 
     public int Qty; 
     public int Target; 
     public string Leader; 
     public string Start; 
     public string End; 
     public int Percent; 
    }  

而且我想更新進入LInfo項目之一的領域「百分比」,我有當前位置(aCurrentLine)。

LInfo.Percent = Convert.ToInt32((RealProduced/DesireProd) * 100);     
Lines[aCurrentLine]....? 

請指教,謝謝。

回答

3

只是

LInfo.Percent = Convert.ToInt32((RealProduced/DesireProd) * 100); 
Lines[aCurrentLine] = LInfo; 

應該工作...但不要使用任何公共領域可變的結構。兩者在可維護性和意想不到的效果方面都很糟糕。

您在C#中創建的大多數類型可能都是類 - 您希望創建值類型(結構)的情況相對較少。你應該確保你知道differences between the two

同樣在C#中的字段應該幾乎總是是私有的。它們應該是類型的實現細節,而不是其公共API的一部分。 Use properties instead - 在C#3中自動實現的屬性使得它們幾乎可以像字段一樣緊湊,如果你只是想要一個平凡的屬性。

+0

太棒了!謝謝,關於可變結構,我需要了解它;) – Somebody

1

我只有一個adivice。可變的結構是邪惡的。儘量避免它。

Lines[aCurrentLine] = LInfo;

您將無法訪問Lines[aCurrentLine].Percent,因爲它只是更新的臨時副本。

+0

謝謝! @Ashley – Somebody

0

用於更新帶網格視圖的通用列表記錄。放入此代碼。

List<Address> people = (List<Address>)Session["People"]; 
     people[e.RowIndex].DoorNo = ((TextBox)grdShow.Rows[e.RowIndex].Cells[2].Controls[0]).Text; 
     people[e.RowIndex].StreetName = ((TextBox)grdShow.Rows[e.RowIndex].Cells[3].Controls[0]).Text; 
     people[e.RowIndex].City = ((TextBox)grdShow.Rows[e.RowIndex].Cells[4].Controls[0]).Text; 
     people[e.RowIndex].PhoneNo = ((TextBox)grdShow.Rows[e.RowIndex].Cells[5].Controls[0]).Text; 
     grdShow.EditIndex = -1; 
     grdShow.DataSource = people; 
     grdShow.DataBind(); 

並將此代碼放入頁面加載事件。

if (!IsPostBack) 
     { 

      List<Address> people = new List<Address>(); 
      Session["People"] = people; 
     } 

使用網格視圖寫上的按鈕事件的代碼創建泛型列表(從文本框中獲取數據並保存在列表中)

GenerateList();//call the method GenerateList(); 

GenerateList的sytex();

private void GenerateList() 
    { 
     if (Session["People"] != null) 
     { 

      List<Address> people = (List<Address>)Session["People"]; 

      Address a1 = new Address(); 

      a1.DoorNo = txtDoorno.Text; 
      a1.StreetName = txtStreetName.Text; 
      a1.City = txtCityname.Text; 
      a1.PhoneNo = txtPhoneno.Text; 
      people.Add(a1); 
      Session["People"] = people; 
      grdShow.DataSource = people; 
      grdShow.DataBind(); 
     } 
    } 
相關問題