Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4861
  • Last Modified:

Drag and Drop from Datagridview in C#

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
tomcahill
Asked:
tomcahill
  • 4
  • 4
1 Solution
 
gbarcalowCommented:
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
 
gbarcalowCommented:
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
 
tomcahillAuthor Commented:
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
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
gbarcalowCommented:
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
 
tomcahillAuthor Commented:
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
 
gbarcalowCommented:
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
 
tomcahillAuthor Commented:
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
 
tomcahillAuthor Commented:
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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now