2011-01-22 91 views
11

我在從datagridview繼承的控件中實現了一些拖放功能。基本上我從DGV的某個地方拖了一行,然後將它放在其他地方,重新排列行。儘管我遇到了問題。如果DGV太大以至於沒有滾動條,那麼當用戶處於拖動中間時,如何讓DGV向上或向下滾動?如何以編程方式滾動winforms datagridview控件?

我知道如何獲得當前的鼠標位置,並獲得dgv矩形等的位置。所以,我可以很容易地發現,如果我在矩形的上半部分或下半部分......我只需要一種以編程方式滾動dgv的方法。我寧願如果我不必改變選定的單元格來做到這一點。

有什麼建議嗎?

感謝

艾薩克

回答

18

那麼,因爲這是一個datagridview ...對不起,對於'winforms'的問題...但我可以這樣做..向上或向下滾動一行。

向上滾動:

this.FirstDisplayedScrollingRowIndex = this.FirstDisplayedScrollingRowIndex - 1 

向下滾動:

this.FirstDisplayedScrollingRowIndex = this.FirstDisplayedScrollingRowIndex + 1; 

你得確保檢查號碼不出門界雖然。

5

你可以做,使用WinAPI的通過發送消息給控制告訴它,或上下滾動。

下面是代碼,我希望它能幫助:

private const int WM_SCROLL = 276; // Horizontal scroll 
private const int WM_VSCROLL = 277; // Vertical scroll 
private const int SB_LINEUP = 0; // Scrolls one line up 
private const int SB_LINELEFT = 0;// Scrolls one cell left 
private const int SB_LINEDOWN = 1; // Scrolls one line down 
private const int SB_LINERIGHT = 1;// Scrolls one cell right 
private const int SB_PAGEUP = 2; // Scrolls one page up 
private const int SB_PAGELEFT = 2;// Scrolls one page left 
private const int SB_PAGEDOWN = 3; // Scrolls one page down 
private const int SB_PAGERIGTH = 3; // Scrolls one page right 
private const int SB_PAGETOP = 6; // Scrolls to the upper left 
private const int SB_LEFT = 6; // Scrolls to the left 
private const int SB_PAGEBOTTOM = 7; // Scrolls to the upper right 
private const int SB_RIGHT = 7; // Scrolls to the right 
private const int SB_ENDSCROLL = 8; // Ends scroll 

[DllImport("user32.dll",CharSet=CharSet.Auto)] 
private static extern int SendMessage(IntPtr hWnd, int wMsg,IntPtr wParam, IntPtr lParam); 

現在,假設你有你的窗體上的文本框控件。您可以將其移動到:

SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEUP,IntPtr.Zero); //ScrollUp 
SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEDOWN,IntPtr.Zero); //ScrollDown 

如果該經典通用解決方案不適用於您。您可能想要查看FirstDisplayedScrollingRowIndex屬性,並在拖動過程中更改您的鼠標位置。

+0

感謝您的支持。我還沒有嘗試過..你上面的那個人沒有winapi這樣做的方式。 – 2011-01-23 07:01:37

+0

試過了,它沒有工作。抱歉! – 2011-01-23 09:01:21

9

您可以通過設置做到這一點的HorizontalScrollingOffset/VerticalScrollingOffsetDataGridView

設置Horizo​​ntalScrollingOffset

dataGridView1.HorizontalScrollingOffset = dataGridView1.HorizontalScrollingOffset + 10; 

檢查

DataGridView.HorizontalScrollingOffset Property

VerticalScrollingOffset您可以使用反射

包括命名空間System.Reflection

PropertyInfo verticalOffset = dataGridView1.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance); 
      verticalOffset.SetValue(this.dataGridView1, 10, null); 
+2

VerticalScrollingOffset具有隻讀屬性。所以你只能`得到'它,不能'設置`它。 – 2011-01-22 06:02:52

2

您需要實現DragOver事件。檢查鼠標是否靠近控件的頂部或底部(使用PointToClient)。如果是,則啓用間隔約爲200毫秒的定時器。在Tick事件處理程序中,滾動DGV一行。當鼠標不關閉並在DoDragDrop返回後禁用定時器。用戶現在可以方便,直觀地滾動網格,只是在端點附近盤旋。

4
dgv.FirstDisplayedScrollingRowIndex = dgv.RowCount - 1;