Problem with checkedListBox + drag-n-drop

Asked

Viewed 30 times

1

Good morning, I have a problem with the component checkedListBox of my application C# Windows Form. In the following code I am using drag n drop to reorder items from checkedListBox, what is working correctly. However I cannot mark how check in no item. I think the problem is in the event MouseDown but I can’t fix it. Someone can help me with this problem?

EDIT: code updated and working correctly.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace projetodetestes
{
public partial class testeeacelerometro : Form
{
    public testeeacelerometro()
    {
        InitializeComponent();
    }

    bool teste_checked = false;

    private void testeeacelerometro_Load(object sender, EventArgs e)
    {
        checkedListBox1.AllowDrop = true;
        checkedListBox1.CheckOnClick = true;
    }

    private void checkedListBox1_DragDrop(object sender, DragEventArgs e)
    {
        Point point = checkedListBox1.PointToClient(new Point(e.X, e.Y));
        int index = this.checkedListBox1.IndexFromPoint(point);
        if (index < 0) index = this.checkedListBox1.Items.Count - 1;
        object data = this.checkedListBox1.SelectedItem;
        this.checkedListBox1.Items.Remove(data);
        this.checkedListBox1.Items.Insert(index, data);
        if (teste_checked == true) checkedListBox1.SetItemChecked(index, true);
        else return;
    }

    private void checkedListBox1_DragOver(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

    private void checkedListBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (this.checkedListBox1.SelectedItem != null && e.Button == MouseButtons.Left)
        {
            int index = checkedListBox1.SelectedIndex;
            if (checkedListBox1.GetItemChecked(index)) teste_checked = true;
            this.checkedListBox1.DoDragDrop(this.checkedListBox1.SelectedItem, DragDropEffects.Move);            
        }
    }
}
}
  • This is happening because you used checkedListBox1.CheckOnClick = false;

  • 1

    it’s not, I tried to leave true but qnd he enters the event Mousedown he starts the drag drop.

1 answer

3


Unfortunately there are not many solutions. There is a gambiarra that works partially.

Remove the event MouseDown and enter the event MouseMove in this way:

private void checkedListBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (this.checkedListBox1.SelectedItem != null && e.Button == MouseButtons.Left)
        this.checkedListBox1.DoDragDrop(this.checkedListBox1.SelectedItem, DragDropEffects.Move);
}

Edit: I say it works partially, because any mouse drive (with the left button pressed) already activates the DragDrop.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.