2011-10-06 48 views
4

我有c#DataGridViews修改,以便我可以拖放它们之间的行。我需要弄清楚如何禁用拖动某些行,或者拒绝这些行的拖放。我使用的标准是数据行中的一个值。拒绝基于对象数据的拖放操作?

我想禁用行(灰色,不允许拖动)作为我的第一选择。

我有什么选择?如何根据条件禁用或拒绝拖放?

+0

您可以在拖动发生后检查行的索引吗?这将是诀窍 – 2011-10-07 16:12:20

+0

@ Mr.DDD - 你可以详细说明一下吗?你在暗示什么? – MAW74656

+0

你在其他人之间拖动行,不是吗?那么,如果您可以检查正在拖动的行的索引(即新行将在其旁边的行),则可以接受/拒绝拖动。这取决于行indeces。 – 2011-10-07 16:20:21

回答

4

如果你想防止一行从根本上被拖动,使用下面的方法来代替:

void dataGridView1_DragEnter(object sender, DragEventArgs e) 
{ 
    DataGridViewRow row = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow)); // Get the row that is being dragged. 
    if (row.Cells[0].Value.ToString() == "no_drag") // Check the value of the row. 
     e.Effect = DragDropEffects.None; // Prevent the drag. 
    else 
     e.Effect = DragDropEffects.Move; // Allow the drag. 
} 

在这里,我想你做这样的事情开始拖动操作:

DoDragDrop(dataGridView1.SelectedRows[0], DragDropEffects.Move); 

在这种情况下,您当然不需要使用我以前答案中的方法。

+0

- 其中dataGridView1是源网格(行开始的地方)?还是在你的例子中的目的地? – MAW74656

+0

它是源网格。 –

+0

- 我仍然缺少一些东西。源网格的DragEnter事件永远不会被触发(因为我从不进入该网格)。 DragOver和DragLeave也不起作用。 – MAW74656

2

下面是一个应该让你开始的示例方法:

void dataGridView1_DragOver(object sender, DragEventArgs e) 
    { 
     Point cp = PointToClient(new Point(e.X, e.Y)); // Get coordinates of the mouse relative to the datagridview. 
     var dropped = dataGridView1.HitTest(cp.X, cp.Y); // Get the item under the mouse pointer. 
     if (dataGridView1.Rows[dropped.RowIndex].Cells[0].Value.ToString() == "not_allowed") // Check the value. 
      e.Effect = DragDropEffects.None; // Indicates dragging onto this item is not allowed. 
     else 
      e.Effect = DragDropEffects.Move; // Set the drag effect as required. 
    } 

你应该的,当然,像这样使用:

dataGridView1.DragOver += new DragEventHandler(dataGridView1_DragOver); 

的if从句您需要在修改状态。目前,如果第一个单元格的值等于“not_allowed”,则禁用拖动到行上。

+0

- 我不太明白......我没有把任何东西拖到一行上,我在datagridviews之间拖动了整行。我不确定这是如何适用的? – MAW74656

+0

@ MAW74656您在您的问题中声明您要禁用在某些行上拖拽**,这就是代码的作用。如果B有特殊值,它可以防止行A被拖到行B上。你是否试图防止行A被拖拽(到什么地方)? –

+0

正确,我想防止一行被基于某些值拖拽(完全)。 – MAW74656