2011-10-06 51 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