小弟编程没多久,有好些程序不知组织的好不好,现在贴出来,想请各路高手帮忙指点一下,谢谢大家了!
  本代码主要是实现从同一个界面上的一个listbox拖一个item到另一个listbox,或是在一个listbox中进行拖放!
  //此处是拖放事件
  private void listBoxUCP_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(System.String)))
            {                object item = e.Data.GetData(typeof(System.String));                // Perform drag-and-drop, depending upon the effect.
                if (e.Effect == DragDropEffects.Move)
                {
                    updateListBoxItems(source, listBoxUCP, item, e);                    
                }
            }
        }
    
    //以下两函数做为拖放事件的子函数
    private void updateListBoxItems(ListBox sourceListBox, ListBox targetListBox, object sourceItem, DragEventArgs e)
        {
            int targetIndex = getTartgetIndexFromPoint(targetListBox, e);
            int sourceIndex = targetListBox.SelectedIndex;            if (sourceListBox == targetListBox)
            {
                if (targetIndex == targetListBox.SelectedIndex)
                    return;
                targetListBox.Items.RemoveAt(sourceIndex);
            }
      //if targetItem != null and insert place not in the end of the itemlist,
           //use the insert method
            if (targetIndex > 0 && targetIndex < targetListBox.Items.Count)
            {
                if (sourceListBox != targetListBox || sourceIndex > targetIndex)
                    targetIndex = targetIndex + 1;
                
                    targetListBox.Items.Insert(targetIndex, sourceItem);
                    targetListBox.SelectedIndex = targetIndex;
                
            }
            //add the item in the end of the itemlist
            else
            {
                targetListBox.Items.Add(sourceItem);
                targetListBox.SelectedIndex = targetListBox.Items.Count - 1;
            }
        }    private int getTartgetIndexFromPoint(ListBox listBox, DragEventArgs e)
        {
            Point position = new Point(e.X, e.Y);
            position = listBox.PointToClient(position);
            return listBox.IndexFromPoint(position);
        }      为了使代码更精练,我总是想方设法尽量不让代码中出现重复的操作或判断语句,但为了这样做,常常觉得做出的逻辑不太合正常的逻辑(也许这样说不对,应该说不太符合一般人的思维逻辑),虽然说正常的逻辑有些重复的操作。请教大家都是怎么做的!