Home > .Net Framework > Drag and Drop di DataGridView

Drag and Drop di DataGridView


Berikut ini kode program sederhana untuk melakukan drag n drop di DataGridView, Event yang penting adalah Mouse Down pada DataGrid sumber dan DragDrop serta DragEnter pada DataGrid tujuan

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DataGridView_dnd
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.Rows.Add("a", "b", "c");

            dataGridView2.AllowDrop = true;
            dataGridView2.Rows.Add("x", "y");
        }
        DataGridViewCell cell;
        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.Cell)
            {
                cell=dataGridView1.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
                dataGridView1.DoDragDrop(cell.Value, DragDropEffects.Copy);
            }
        }

        private void dataGridView2_DragDrop(object sender, DragEventArgs e)
        {

            Point clientPoint = dataGridView2.PointToClient(new Point(e.X, e.Y));
            DataGridView.HitTestInfo hit = dataGridView2.HitTest(clientPoint.X, clientPoint.Y);
            if (hit.Type == DataGridViewHitTestType.Cell)
            {
                cell = dataGridView2.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
                cell.Value = e.Data.GetData(typeof(string));
            }
        }

        private void dataGridView2_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(string)))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
    }
}
Categories: .Net Framework
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: