Solved

Drag and Drop from Datagridview in C#

Posted on 2008-06-10
8
4,686 Views
Last Modified: 2008-07-10
I have an application with a treeview and a datagrid, both are databound.

The treeview lists orders and below each order lists the packages in each order.  The orders can be schemed based on lanes the products are being shipped on.

By default the treeview shows order number, unschemed , product.

When clicking on the order number node the datagrid view shows all the products in that order.

I want to be able to right click on an order and click on "Add Scheme" then have the program query a database table for the lane numbers and add children to the order number node named "Lane 1", "Lane 2", etc...  Then I would like to be able select the products I want to go down a certain lane, drag them onto that lane, and have the program automatically modifiy the product database to indicate the new lane.  When the datagrid is refreshed those orders should now show up under their proper lane and not the unschemed node.

Getting the drag an drop to work from the datagridview to the treeview is where I am really lost.  Although I would appreciate input on the other steps I am really in need of help on this one part.
0
Comment
Question by:tomcahill
  • 4
  • 4
8 Comments
 
LVL 3

Expert Comment

by:gbarcalow
ID: 21752379
I had a problem with dragging from the DataGridView and finally I had to settle on it being a right-click drag and drop. All you have to do is invoke the DoDragDrop method on the DataGridView. Then look for the right object type being passed into the treeview.

See the code for a small example...

private void dataGrid_MouseDown(object sender, MouseEventArgs e)

{

    int[] rowIDs = new int[dataGrid.SelectedRows.Count];

    for (int i = 0; i != dataGrid.SelectedRows.Count; i++)

    {

        rowIDs[i] = dataGrid.SelectedRows.Cells[0];

    }

    dataGrid.DoDragDrop(rowIDs, DragDropEffected.Link);

}

Open in new window

0
 
LVL 3

Expert Comment

by:gbarcalow
ID: 21752388
I am sorry, I forgot to include to code the check if it's the right mouse button.
private void dataGrid_MouseDown(object sender, MouseEventArgs e)

{

    if (e.Button == MouseButtons.Right)

    {

        int[] rowIDs = new int[dataGrid.SelectedRows.Count];

        for (int i = 0; i != dataGrid.SelectedRows.Count; i++)

        {

            rowIDs[i] = dataGrid.SelectedRows.Cells[0];

        }

        dataGrid.DoDragDrop(rowIDs, DragDropEffected.Link);

    }

}

Open in new window

0
 
LVL 9

Author Comment

by:tomcahill
ID: 21752751
I receive the following errors:

Error      1      'System.Windows.Forms.DataGridViewSelectedRowCollection' does not contain a definition for 'Cells' and no extension method 'Cells' accepting a first argument of type 'System.Windows.Forms.DataGridViewSelectedRowCollection' could be found (are you missing a using directive or an assembly reference?)      C:\Users\tom\Documents\Visual Studio 2008\Projects\IOPS\IOPS\Form1.cs      680      60      IOPS
Error      2      The name 'DragDropEffected' does not exist in the current context      C:\Users\tom\Documents\Visual Studio 2008\Projects\IOPS\IOPS\Form1.cs      682      50      IOPS
0
 
LVL 3

Expert Comment

by:gbarcalow
ID: 21752928
Sorry about my types, I didnt have access to VS at the time.
Error 1: should be

rowIDs[i] = dataGrid.SelectedRows[i].Cells[0];
 

Error 2: should be

dataGrid.DoDragDrop(rowIDs, DragDropEffects.Link);

Open in new window

0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 9

Author Comment

by:tomcahill
ID: 21754659
great, now I get the error:

Error      1      Cannot implicitly convert type 'System.Windows.Forms.DataGridViewCell' to 'int'      C:\Users\tom\Documents\Visual Studio 2008\Projects\IOPS\IOPS\Form1.cs      680      33      IOPS

on the line:

rowIDs[i] = dataGridView1.SelectedRows[i].Cells[0];

do I need to add .rowindex ??
0
 
LVL 3

Expert Comment

by:gbarcalow
ID: 21754704
What does the data that you loading into the datagridview look like? What is your datasource and whats in it, and which fields are your keys?
0
 
LVL 9

Author Comment

by:tomcahill
ID: 21833173
My datasource is a dataset loaded from a SQL table.  The primary key, and only key, is a Column named CAT that is numeric.  It is an Identity column.

Sorry for the delay in responding.  

0
 
LVL 9

Accepted Solution

by:
tomcahill earned 0 total points
ID: 21917152
I found how to make it work.

my datagrid is named grdCampaigns

my treeview is named lstCategories

I create a 2 global variables as such:
bool dragdrop = false;

DataGridViewSelectedRowCollection myRows;

When I do the drag and drop I move the selected rows from the datagrid to the myRows variable.  then in the drop I use that information to populate the treeview.


I will attach all of my code.

namespace Drag_Drop_Test

{

    public partial class Form1 : Form

    {

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]

        public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
 

        private const int MOUSEEVENTF_LEFTDOWN = 0x02;

        private const int MOUSEEVENTF_LEFTUP = 0x04;

        private const int MOUSEEVENTF_RIGHTDOWN = 0x08;

        private const int MOUSEEVENTF_RIGHTUP = 0x10;

        bool dragdrop = false;
 

        DataGridViewSelectedRowCollection myRows;
 

        
 
 

        public Form1()

        {

            InitializeComponent();

        }
 

        private void Form1_Load(object sender, EventArgs e)

        {

            // TODO: This line of code loads data into the 'iOPS_SandboxDataSet.CarrierMaster' table. You can move, or remove it, as needed.

            this.carrierMasterTableAdapter.Fill(this.iOPS_SandboxDataSet.CarrierMaster);

            
 

        }
 

        private void grdCampaigns_MouseDown(object sender, MouseEventArgs e)

        {

            DataGridView.HitTestInfo info = grdCampaigns.HitTest(e.X, e.Y);

            if (info.RowIndex >= 0)

            {

                DataRowView view = (DataRowView)

                grdCampaigns.Rows[info.RowIndex].DataBoundItem;
 

                if (view != null)

                    grdCampaigns.DoDragDrop(view, DragDropEffects.Copy);

            }

        }
 

        private void lstCategories_DragEnter(object sender, DragEventArgs e)

        {           

            e.Effect = DragDropEffects.Copy;

        }
 

         public void DoMouseClick()

        {

            

            //Call the imported function with the cursor's current position

            int X = Cursor.Position.X;

            int Y = Cursor.Position.Y;

            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
 

        }
 

        private void lstCategories_DragDrop(object sender, DragEventArgs e)

        {

            myRows = grdCampaigns.SelectedRows;

            DoMouseClick();

            dragdrop = true;

        }
 

        private void updateTree()

        {

            if(lstCategories.SelectedNode.Level == 2)

            {

                TreeNode selectedNode = lstCategories.SelectedNode;

            

                lstCategories.BeginUpdate();

                for (int i = 0; i < myRows.Count; i++)

            {

                selectedNode.Nodes.Add(myRows[i].Cells[1].Value.ToString());

            }

                lstCategories.EndUpdate();

                dragdrop = false;

                grdCampaigns.Refresh();

            }

            

        }
 
 
 

        private void lstCategories_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)

        {

            if (dragdrop)

            {

                updateTree();

            }

  

        }
 

        private void addSchemeToolStripMenuItem_Click(object sender, EventArgs e)

        {

            

            TreeNode baseNode = lstCategories.SelectedNode;

            baseNode.Nodes.Add("Scheme","Scheme");

            TreeNode schemeNode = baseNode.Nodes["Scheme"];
 

            string connectionString = Drag_Drop_Test.Properties.Settings.Default.IOPS_SandboxConnectionString;
 

            string selectString = "Select * from SchemeTypeMaster WHERE STYP = '1'";
 

            SqlConnection myConnection = new SqlConnection(connectionString);

            myConnection.Open();
 

            SqlCommand schemeCommand = new SqlCommand(selectString, myConnection);

            SqlDataReader schemeReader = schemeCommand.ExecuteReader();
 

            while (schemeReader.Read())

            {

                schemeNode.Nodes.Add(schemeReader["OLAN"].ToString().Trim(), schemeReader["LNAM"].ToString().Trim());

            }

            schemeCommand.Dispose();

            myConnection.Close();

            baseNode.ExpandAll();

            baseNode.ContextMenuStrip = null;

            

        }

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show, step by step, how to integrate R code into a R Sweave document
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now