[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Drag and Drop from Datagridview in C#

Posted on 2008-06-10
8
Medium Priority
?
4,821 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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 Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
Suggested Courses

656 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