Click here to Skip to main content
15,886,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to drag contents from one cell to another cell within the same datagridview in C#.net
Any Help??

Thanx in advance
Posted

1 solution

there are a couple of articles on codeproject and google that address this issueDrag and Drop between list boxes - Beginner's Tutorial[^]

and particularly for datagridview ... its not that much different... this code might help you

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

            //allow drop
            this.dataGridView1.AllowDrop = true;

            //data grid view sample data 
            DataTable dtb = new DataTable();
            dtb.Columns.AddRange(new DataColumn[] { new DataColumn(), new DataColumn(), new DataColumn() });
            
            for (int i = 0; i < 30;)
            {
                dtb.Rows.Add((++i).ToString(), (++i).ToString(), (++i).ToString());    
            }
            dataGridView1.DataSource = dtb;
        }

        private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                dataGridView1.DoDragDrop(dataGridView1[e.ColumnIndex,e.RowIndex].FormattedValue, DragDropEffects.Copy);
            }
        }

        private void dataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            string cellvalue=e.Data.GetData(typeof(string)) as string;
            Point cursorLocation=this.PointToClient(new Point(e.X,e.Y));

            System.Windows.Forms.DataGridView.HitTestInfo hittest= dataGridView1.HitTest(cursorLocation.X,cursorLocation.Y);
            if (hittest.ColumnIndex != -1
                && hittest.RowIndex != -1)
                dataGridView1[hittest.ColumnIndex, hittest.RowIndex].Value = cellvalue;
        }

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



good luck
 
Share this answer
 
Comments
Member 11691476 24-Aug-16 17:33pm    
The code works fine, but I have a different need, I need to move between two cells in the same row, I mean , whatever the user put the mouse , the drop will have to be done in the same row from where he made the drag .

¿How can I get the rowindex of the row from which I do the drag ?

Thanks

Nestor

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900