2011-01-30 42 views
0

我想了解這裏發生了什麼。我有一個CheckedListBox,其中包含一些打勾的和一些未勾選的項目。我試圖找到一種方法來確定選擇控件中的增量。我已經嘗試過一些這樣的繁瑣工作 - 但只適用於部分時間,我敢肯定還有更優雅的解決方案。一個可能相關的問題是myCheckBox_ItemCheck事件在表單加載時觸發 - 在我有機會執行ItemCheck之前。這是我到目前爲止有:c#事件觸發Windows窗體不正確

void clbProgs_ItemCheck(object sender, ItemCheckEventArgs e) 
    { 
     // i know its awful 

     System.Windows.Forms.CheckedListBox cb = (System.Windows.Forms.CheckedListBox)sender; 

     string sCurrent = e.CurrentValue.ToString(); 
     int sIndex = e.Index; 
     AbstractLink lk = (AbstractLink)cb.Items[sIndex]; 

     List<ILink> _links = clbProgs.DataSource as List<ILink>; 

     foreach (AbstractLink lkCurrent in _links) 
     { 

      if (!lkCurrent.IsActive) 
      { 
       if (!_groupValues.ContainsKey(lkCurrent.Linkid)) 
       { 
        _groupValues.Add(lkCurrent.Linkid, lkCurrent); 
       } 
      } 
     } 

     if (_groupValues.ContainsKey(lk.Linkid)) 
     { 
      AbstractLink lkDirty = (AbstractLink)lk.Clone(); 

      CheckState newValue = (CheckState)e.NewValue; 
      if (newValue == CheckState.Checked) 
      { 
       lkDirty.IsActive = true; 

      } 
      else if (newValue == CheckState.Unchecked) 
      { 
       lkDirty.IsActive = false; 
      } 

      if (_dirtyGroups.ContainsKey(lk.Linkid)) 
      { 
       _dirtyGroups[lk.Linkid] = lkDirty; 
      } 
      else 
      { 
       CheckState oldValue = (CheckState)e.NewValue; 
       if (oldValue == CheckState.Checked) 
       { 
        lkDirty.IsActive = true; 

       } 
       else if (oldValue == CheckState.Unchecked) 
       { 
        lkDirty.IsActive = false; 
       } 

       _dirtyGroups.Add(lk.Linkid, lk); 
      } 

     } 
     else 
     { 
      if (!lk.IsActive) 
      { 
       _dirtyGroups.Add(lk.Linkid, lk); 
      } 
      else 
      { 
       _groupValues.Add(lk.Linkid, lk); 
      } 
     } 
    } 

隨後的onclick保存按鈕的 - 我檢查什麼發送到數據庫之前改變:

private void btSave_Click(object sender, EventArgs e) 
    { 

     List<AbstractLink> originalList = new List<AbstractLink>(_groupValues.Values); 
     List<AbstractLink> changedList = new List<AbstractLink>(_dirtyGroups.Values); 

     IEnumerable<AbstractLink> dupes = originalList.ToArray<AbstractLink>().Intersect(changedList.ToArray<AbstractLink>()); 

     foreach (ILink t in dupes) 
     { 
      MessageBox.Show("Changed"); 
     } 
     if (dupes.Count() == 0) 
     { 
      MessageBox.Show("No Change"); 
     } 
    } 

如需進一步信息。 AbstractLink類型的定義使用:

public bool Equals(ILink other) 
    { 
     if (Object.ReferenceEquals(other, null)) return false; 
     if (Object.ReferenceEquals(this, other)) return true; 
     return IsActive.Equals(other.IsActive) && Linkid.Equals(other.Linkid); 
    } 

回答

1

我覺得在ItemCheck事件中這樣做的意義不大。保存時只需計算增量。刪除了一堆代碼和麻煩事件的麻煩。