Solved

Drag and Drop from Datagridview in C#

Posted on 2008-06-10
8
4,669 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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

760 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

18 Experts available now in Live!

Get 1:1 Help Now