Drag-n-Drop operation is an important action in the winforms application like our file explorer. This article will let you perform moving items from one datagridview to another, code is in c#. Follow the article and you will easily be able to do this task.
There are series of events that need to be handled to complete this task, discussed in moving items from one CheckedListBox to another. To perform this in datagridview we will use the pre-defined class Student with its properties like name, age and address.
Run the project, defaultDGV have three rows added above, perform your drag-n-drop operation, it will successfully move the record.
There are series of events that need to be handled to complete this task, discussed in moving items from one CheckedListBox to another. To perform this in datagridview we will use the pre-defined class Student with its properties like name, age and address.
- Add two DataGridView control to the form (defaultDGV & newDGV) and place them in simple form as shown.
- Create two list of type Student class named stuList and newList.
List<Student> stuList = new List<Student>();
List<Student> newList = new List<Student>(); - In the constructor add some records in the first list and bind that to first datagridview.
public Form1()
{
InitializeComponent();
stuList.Add(new Student() { Name = "Jacob", Age = 29, City = "London" });
stuList.Add(new Student() { Name = "Zulia", Age = 31, City = "London" });
stuList.Add(new Student() { Name = "Brandon", Age = 35, City = "London" });
defaultDGV.DataSource = stuList;
} - Generate MouseDown event of the defaultDGV datagridview and write following code:
if (defaultDGV.SelectedRows.Count == 1)
{
if (e.Button == MouseButtons.Left)
{
DataGridView.HitTestInfo info = defaultDGV.HitTest(e.X, e.Y);
if (info.RowIndex >= 0)
{
string name = defaultDGV.Rows[info.RowIndex].Cells["Name"].Value.ToString();
defaultDGV.DoDragDrop(name, DragDropEffects.Move);
}
}
}
- Generate DragEnter and DragDrop events of another datagridview i.e. newDGV and make them same as written with following c# code.
private void newDGV_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void newDGV_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
string str = (string)e.Data.GetData(typeof(string));
var record = stuList.FirstOrDefault(a => a.Name.Equals(str));
stuList.Remove(record);
newList.Add(record);
defaultDGV.DataSource = newDGV.DataSource = null;
defaultDGV.DataSource = stuList;
newDGV.DataSource = newList;
}
}
Run the project, defaultDGV have three rows added above, perform your drag-n-drop operation, it will successfully move the record.
Tidak ada komentar:
Posting Komentar