2014-10-27 34 views
0

使用VS C#winform .NET 4.0。列表变量改变都在C#winform中分配

我在c#上很新。我有一个程序使用DateTimePicker和ComboBoxes检查可用时间。 二进制列表AppVars._EventList没有值,所以它是无关紧要的。

我的问题是与列表sTimes, sT & sE。当我将cbxStartTime更改为06:00时,它不仅从sT中删除字符串05,而且从所有列表中删除字符串05。这个结果的效果是,如果选择了新的日期,则05时隙将不在那里。

这是为什么,我该如何解决?

List<string> sTimes = new List<string>() { "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22" }; 
    List<string> sE; 

    private void dtpStartDate_ValueChanged(object sender, EventArgs e) 
    { 
     cbxEndTime.Items.Clear(); 
     cbxStartTime.Items.Clear(); 
     List<string> sT = sTimes; 
     foreach (Events evt in AppVars._EventList) 
      foreach (string s in sT) 
       if (evt.StartDateTime.Date.ToString("yyyy/MM/dd") == dtpStartDate.Value.ToString("yyyy/MM/dd") && evt.StartDateTime.Hour.ToString("HH") == s) 
        sT.Remove(s); 
     int iSmall = Convert.ToInt32(sT[0]); 
     foreach (string s in sT) 
     { 
      cbxStartTime.Items.Add(Convert.ToInt32(s) + ":00"); 
      if (iSmall + 1 == Convert.ToInt32(s)) 
       iSmall++; 
     } 
     for (int s = Convert.ToInt32(sT[0]); s <= iSmall + 1; s++) 
      cbxEndTime.Items.Add(Convert.ToInt32(s) + 1 + ":00"); 
     if (cbxStartTime.Items.Count == 0) 
      epdTime.SetError(cbxStartTime, "No Time slots available for this day"); 
     sE = sT; 
    } 

    private void cbxStartTime_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     List<string> sT = sE; 
     cbxEndTime.Items.Clear(); 
     foreach (string item in sT.ToList())//change happens here 
      if (Convert.ToDateTime("2001/01/01 " + cbxStartTime.SelectedItem) > Convert.ToDateTime("2001/01/01 " + item + ":00")) 
       sT.Remove(item); 
     int iSmall = Convert.ToInt32(sT[0]); 
     foreach (string s in sT) 
      if (iSmall + 1 == Convert.ToInt32(s)) 
       iSmall++; 
     for (int s = Convert.ToInt32(sT[0]); s <= iSmall; s++) 
      cbxEndTime.Items.Add(Convert.ToInt32(s) + 1 + ":00"); 
    } 
+1

sT,sTimes和sE都表示同一个对象。如果您删除了一个项目,它将反映在对该列表的所有引用中。 – 2014-10-27 14:53:03

+0

@eddie_cat我明白了,我怎么才能从一个列表中删除呢? – sgtBlueBird 2014-10-27 14:56:25

+0

http://www.albahari.com/valuevsreftypes.aspx – Steve 2014-10-27 14:56:25

回答

2
List<string> sT = sTimes; 

是问题,

你想List<string> sT = new List<string>(sTimes);

也就是说你想操纵你的原始列表的副本,而不是名单本身。