Hi,
->InvalidCastException was unhandled
Unable to cast object of type 'modelClasses.mediaobject' to type 'system.data.data.datarowview'.
->DataGridViewRow view = (DataGridViewRow)dgvObjects.Rows[info.RowIndex].DataBoundItem;
Because the DataGridView is bound to an object typed of modelClasses.mediaobject. You can changed this to:
modelClasses.mediaobject cdrag = dgvObjects.Rows[info.RowIndex].DataBoundItem as modelClasses.mediaobject;
Besides, in lbObjects_DragDrop event, you need also modify the type.
I write the following example for you. Hope this helps.
private void Form2_Load(object sender, EventArgs e)
{
dgvObjects.AllowDrop = true;
lbObjects.AllowDrop = true;
List<Custom> listsource = new List<Custom>();
listsource.Add(new Custom(1, "user1"));
listsource.Add(new Custom(2, "user2"));
listsource.Add(new Custom(3, "user3"));
listsource.Add(new Custom(4, "user4"));
dgvObjects.DataSource = listsource;
dgvObjects.AllowDrop = true;
lbObjects.AllowDrop = true;
dgvObjects.MouseDown += new MouseEventHandler(dgvObjects_MouseDown);
lbObjects.DragEnter += new DragEventHandler(lbObjects_DragEnter);
lbObjects.DragDrop += new DragEventHandler(lbObjects_DragDrop);
}
private void dgvObjects_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
DataGridView.HitTestInfo info = dgvObjects.HitTest(e.X, e.Y);
if (info.RowIndex >= 0)
{
Custom cdrag = dgvObjects.Rows[info.RowIndex].DataBoundItem as Custom;
if (cdrag != null)
dgvObjects.DoDragDrop(cdrag, DragDropEffects.Copy);
}
}
}
private void lbObjects_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void lbObjects_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Custom)))
{
Point p = lbObjects.PointToClient(new Point(e.X, e.Y));
int index = lbObjects.IndexFromPoint(p);
Console.WriteLine(index.ToString());
// if drag to the remain place of the listbox, the index is -1
if (index == -1)
index = lbObjects.Items.Count - 1;
Custom objects = e.Data.GetData(typeof(Custom)) as Custom;
int newID = int.Parse(lbObjects.Items[index].ToString());
int oldID = objects.ID;
if (oldID != newID)
{
//objects.BeginEdit();
objects.ID = newID;
//objects.EndEdit();
}
}
}
}
public class Custom
{
public Custom()
{
this._ID = -1;
this._Name = "User";
}
public Custom(int id, string name)
{
this._ID = id;
this._Name = name;
}
private int _ID;
private string _Name;
public int ID
{
get { return _ID; }
set { _ID = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
Best regards,
Ling Wang
Please remember to click “Mark as Answer�on the post that helps you, and to click “Unmark as Answer�if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.