Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > .NET Frameworks (точка нет фреймворки) > Базы данных (ADO.NET, LinqToSql, ORM Entity Framework, NHibernate)
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 29.03.2013, 01:50   #1
Serhantes
 
Регистрация: 29.02.2012
Сообщений: 3
По умолчанию Drag&Drop строк в dataGridView со связанной БД

Всем добрый вечер.

Нужно реализовать перетаскивание строк в таблице. Нашел в одном месте пример:

Код:
private Rectangle dragBoxFromMouseDown;
private int rowIndexFromMouseDown;
private int rowIndexOfItemUnderMouseToDrop;
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
    if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        // If the mouse moves outside the rectangle, start the drag.
        if (dragBoxFromMouseDown != Rectangle.Empty &&
            !dragBoxFromMouseDown.Contains(e.X, e.Y))
        {

            // Proceed with the drag and drop, passing in the list item.                    
            DragDropEffects dropEffect = dataGridView1.DoDragDrop(
    		dataGridView1.Rows[rowIndexFromMouseDown],
    		DragDropEffects.Move);
        }
    }
}

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    // Get the index of the item the mouse is below.
    rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (rowIndexFromMouseDown != -1)
    {
        // Remember the point where the mouse down occurred. 
     // The DragSize indicates the size that the mouse can move 
     // before a drag event should be started.                
        Size dragSize = SystemInformation.DragSize;

        // Create a rectangle using the DragSize, with the mouse position being
        // at the center of the rectangle.
        dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
                                                       e.Y - (dragSize.Height / 2)),
    						dragSize);
    }
    else
        // Reset the rectangle if the mouse is not over an item in the ListBox.
        dragBoxFromMouseDown = Rectangle.Empty;
}

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

private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
    // The mouse locations are relative to the screen, so they must be 
    // converted to client coordinates.
    Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));

    // Get the row index of the item the mouse is below. 
    rowIndexOfItemUnderMouseToDrop =
        dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

    // If the drag operation was a move then remove and insert the row.
    if (e.Effect== DragDropEffects.Move)
    {
        DataGridViewRow rowToMove = e.Data.GetData(
    		typeof(DataGridViewRow)) as DataGridViewRow;
        dataGridView1.Rows.RemoveAt(rowIndexFromMouseDown);
        dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);

    }
}
Если создавать пустой dataGridView, не задавая ему никакого DataSource'а и вручную вставлять строки, то все работает. Тем не менее, мне нужно оперировать с таблицей, которая связана с access-файлом. В моем случае у datagridview DataSource присваивается BindingSource, создаваемый в процессе выполнения кода. Приведенный выше алгоритм на нем не работает: когда перетаскиваешь строку, она только исчезает, при этом не появляется на месте, куда ты ее перетащил. Т.е. предпоследняя строчка выполняется, а последняя просто игнорируется. Причем, если дальше что-нибудь после этой строчки дописывать в пределах фигурных скобок (какой-нибудь банальный мэссаджбокс например), это тоже будет игнорироваться, что мне совсем не понятно.
Кто-нибудь сталкивался с подобной проблемой? Как сделать нормальное перетаскивание? При этом нужно, чтобы смена порядка строк никак не сказывалась на саму таблицу в исходной БД, т.е. чтобы все это оставалось только в датагридвью.
Буду крайне признателен любому дельному совету.
Serhantes вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
WinForms PictureBox VC++ Drag&Drop _Alerter_ Windows Forms 4 27.05.2011 10:38
Drag&Drop Guzal Qt и кроссплатформенное программирование С/С++ 0 12.04.2011 01:19
drag&drop БАО Общие вопросы C/C++ 2 06.05.2010 12:17
Нужна помощь (Drag-And-Drop & Drag-Abd-Dock)) Arkuz Общие вопросы Delphi 1 18.04.2009 00:15
Drag&Drop shtuceron Общие вопросы Delphi 3 09.04.2008 19:04