Drag, Drop and Move Items from One CheckedListBox to Another using Windows Forms

Posted by: Suprotim Agarwal , on 8/2/2008, in Category WinForms & WinRT
Views: 40073
Abstract: In this article, we will explore how to drag, drop and move items from one checkedlistbox to another.
Drag, Drop and Move Items from One CheckedListBox to Another using Windows Forms
 
In this article, we will explore how to drag, drop and move items from one checkedlistbox to another. Follow these steps:
Step 1: Open Visual Studio > File > New > Project. In the Project Types pane, choose the language of your choice (Visual C# or Visual Basic). In the Templates pane, choose Windows Application. Choose a name and location for the project and click OK.
Step 2: Now Drag and Drop two checkedlistbox controls (checkedListBoxA and checkedListBoxB) to the form. We will first preload the checkedListBoxA with a few items and then at runtime, drag, drop and move the items to checkedListBoxB. The items can be moved back again to checkedListBoxA as well. We will be handling 3 events primarily during the entire drag drop operation. The events are as follows:
CheckedListBox MouseDown Event – this event will be handled when the mouse pointer is over the CheckedListBox Item and a mouse button is pressed.
CheckedListBox DragOver Event – this event will be handled when the item is dragged over the destination checkedlistbox
CheckedListBox DragDrop Event - this event will be handled when a drag-and-drop operation is completed.
Step 3: Now let us move ahead and add some code to the form. In the Form1.cs or Form1.vb, add the following code in the constructor of the Form:
C#
int itemIndex;
 
public Form1()
{
    InitializeComponent();
    checkedListBoxA.MouseDown += new MouseEventHandler(checkedListBox_MouseDown);
    checkedListBoxA.DragOver += new DragEventHandler(checkedListBox_DragOver);
    checkedListBoxA.DragDrop += new DragEventHandler(checkedListBox_DragDrop);
    checkedListBoxB.MouseDown += new MouseEventHandler(checkedListBox_MouseDown);
    checkedListBoxB.DragOver += new DragEventHandler(checkedListBox_DragOver);
    checkedListBoxB.DragDrop += new DragEventHandler(checkedListBox_DragDrop);
    checkedListBoxA.AllowDrop = true;
    checkedListBoxB.AllowDrop = true;
}
 
private void Form1_Load(object sender, EventArgs e)
{
    checkedListBoxA.Items.Add("Item 1");
    checkedListBoxA.Items.Add("Item 2");
    checkedListBoxA.Items.Add("Item 3");
    checkedListBoxA.Items.Add("Item 4");
    checkedListBoxA.Items.Add("Item 5");
    checkedListBoxA.Items.Add("Item 6");
}
VB.NET
Private itemIndex As Integer
 
Public Sub New()
      InitializeComponent()
      AddHandler checkedListBoxA.MouseDown, AddressOf checkedListBox_MouseDown
      AddHandler checkedListBoxA.DragOver, AddressOf checkedListBox_DragOver
      AddHandler checkedListBoxA.DragDrop, AddressOf checkedListBox_DragDrop
      AddHandler checkedListBoxB.MouseDown, AddressOf checkedListBox_MouseDown
      AddHandler checkedListBoxB.DragOver, AddressOf checkedListBox_DragOver
      AddHandler checkedListBoxB.DragDrop, AddressOf checkedListBox_DragDrop
      checkedListBoxA.AllowDrop = True
      checkedListBoxB.AllowDrop = True
End Sub
 
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
      checkedListBoxA.Items.Add("Item 1")
      checkedListBoxA.Items.Add("Item 2")
      checkedListBoxA.Items.Add("Item 3")
      checkedListBoxA.Items.Add("Item 4")
      checkedListBoxA.Items.Add("Item 5")
      checkedListBoxA.Items.Add("Item 6")
End Sub
 
In the code above, we are registering the MouseDown, DragOver and DragDrop events for the two CheckedListBox and in the Form_Load, we pre-populate the checkedListBoxA with a few items.
Step 4: Let us now add code to the respective events that were discussed above:
C#
private void checkedListBox_MouseDown(object sender, MouseEventArgs e)
{
    CheckedListBox clb = sender as CheckedListBox;
    itemIndex = clb.IndexFromPoint(e.X, e.Y);
    if (itemIndex >= 0 & e.Button == MouseButtons.Left)
    {
        clb.DoDragDrop(clb.Items[itemIndex], DragDropEffects.Move);
    }
}
 
private void checkedListBox_DragOver(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(typeof(System.String)))
    {
        e.Effect = DragDropEffects.Move;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}
 
private void checkedListBox_DragDrop(object sender, DragEventArgs e)
{
    CheckedListBox clbSender = sender as CheckedListBox;
    clbSender.Items.Add(e.Data.GetData(typeof(System.String)).ToString());
 
    if(clbSender.Name == "checkedListBoxA")
        checkedListBoxB.Items.RemoveAt(itemIndex);
    else
        checkedListBoxA.Items.RemoveAt(itemIndex);
}
VB.NET
Private Sub checkedListBox_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
      Dim clb As CheckedListBox = TryCast(sender, CheckedListBox)
      itemIndex = clb.IndexFromPoint(e.X, e.Y)
      If itemIndex >= 0 And e.Button = MouseButtons.Left Then
            clb.DoDragDrop(clb.Items(itemIndex), DragDropEffects.Move)
      End If
End Sub
 
Private Sub checkedListBox_DragOver(ByVal sender As Object, ByVal e As DragEventArgs)
      If e.Data.GetDataPresent(GetType(System.String)) Then
            e.Effect = DragDropEffects.Move
      Else
            e.Effect = DragDropEffects.None
      End If
End Sub
 
Private Sub checkedListBox_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs)
      Dim clbSender As CheckedListBox = TryCast(sender, CheckedListBox)       clbSender.Items.Add(e.Data.GetData(GetType(System.String)).ToString())
 
      If clbSender.Name = "checkedListBoxA" Then
            checkedListBoxB.Items.RemoveAt(itemIndex)
      Else
            checkedListBoxA.Items.RemoveAt(itemIndex)
      End If
End Sub
Since we are enabling drag, drop and move on both the CheckedListBox, there will be a lot of common code required for the two. So it makes a lot of sense to define generic event handlers.
In the checkedListBox_MouseDown event, we first cast the sender as a CheckedListBox and then retrieve the index of the item using IndexFromPoint(). The index retrieved, is the item selected by the user, to be dragged. We then call the DoDragDrop() method on the sender. This method begins a drag and drop operation and accepts a parameter of the object(checkedlistbox item) that is being dragged. The second parameter describes the effect of a drag drop.
In the checkedListBox_DragOver we check to see if the item being dragged is a valid drop target.
Finally in the checkedListBox_DragDrop, we first cast the sender as a CheckedListBox, retrieve the dragged item using e.Data.GetData() and then add the retrieved item to the checkedListBox items collection. To give it a move effect, we remove the item that was dragged from the sender checkedlistbox.
That’s it. Run the sample and you will be able to perform drag, drop and move operations on the CheckedListBox. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.  
 
What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Nithya K on Wednesday, October 8, 2008 7:54 AM
i have done this application,Thank you very much
Comment posted by Hossein on Tuesday, January 27, 2009 9:28 AM
Thnx buddy, Sample works fine
Comment posted by Nostromo on Tuesday, February 9, 2010 7:04 AM
There's a problem with that sample. If the property "CheckOnClick" of the used CheckedListboxes is set to true, the code in the MouseDown event prevents the checking on the first click. Any suggestions to make that work?
Comment posted by Vali Tuguran on Monday, January 19, 2015 3:13 AM
The thread that runs the code needs to have this attribute set: STAThreadAttribute

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook