[英]DataGridView Handle OnHandleCreate Resetting Selected Rows
我們有一個Microsoft EXCEL COM加載項,可以為用戶創建TaskPane。 根據用戶加載的“插件”,用相應的UserControl填充TaskPane,然后將其顯示在屏幕上。
這些UserControl通常涉及DataGridViews的使用,並且我們保存用戶選擇的行,以便每次加載插件時,都已經為用戶選擇了先前選擇的行。
但是,我們發現,在將UserControl加載到TaskPane並使TaskPane可見的過程中,觸發了多個外部代碼方法,這些方法重置了datagridview的選擇。 以下是這些事件:
System.Windows.Forms.dll!System.Windows.Forms.DataGridView.OnSelectionChanged(System.EventArgs e) + 0x88 bytes
System.Windows.Forms.dll!System.Windows.Forms.DataGridView.FlushSelectionChanged () + 0x37 bytes
System.Windows.Forms.dll!System.Windows.Forms.DataGridView.ClearSelection(int columnIndexException, int rowIndexException, bool selectExceptionElement) + 0x304 bytes
System.Windows.Forms.dll!System.Windows.Forms.DataGridView.SetAndSelectCurrentCellAddress(int columnIndex, int rowIndex, bool setAnchorCellAddress, bool validateCurrentCell, bool throughMouseClick, bool clearSelection, bool forceCurrentCellSelection) + 0x60 bytes
System.Windows.Forms.dll!System.Windows.Forms.DataGridView.MakeFirstDisplayedCellCurrentCell(bool includeNewRow) + 0x88 bytes
System.Windows.Forms.dll!System.Windows.Forms.DataGridView.OnHandleCreated(System.EventArgs e) + 0x3d bytes
System.Windows.Forms.dll!System.Windows.Forms.Control.WmCreate(ref System.Windows.Forms.Message m) + 0x43 bytes
System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message m) + 0x2ed bytes
System.Windows.Forms.dll!System.Windows.Forms.DataGridView.WndProc(ref System.Windows.Forms.Message m) + 0x10a bytes
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage(ref System.Windows.Forms.Message m) + 0x11 bytes
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.Windows.Forms.Message m) + 0x39 bytes System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg, System.IntPtr wparam, System.IntPtr lparam) + 0x5e bytes
實際的代碼更加復雜,涉及到數據庫的調用,但是作為示例,這說明了我們如何創建DGV,然后填充並選擇行。 下面的代碼將遵循UserControl構造函數中的InitializeComponents()
方法:
dgvExample.Rows.Add("Actuals")
dgvExample.Rows.Add("Budget")
dgvExample.Rows.Add("Forecast")
dgvExample.Rows.Add("LY Actuals")
For i = 0 To dgvExample.Rows.Count - 1
dgvExample.Rows(i).Selected = True
Next
我們不希望在TaskPane可見后再移動選擇行的過程,因為用戶將看到更改,而且對於最終用戶而言,外觀也不是很干凈。 一旦將選定行的實例化DGV對象添加到TaskPane中,它將不保存這些值是沒有意義的。
正如您所診斷的那樣,HandleCreated事件清除了Selection,因此解決方案是在設置所選項目之前,在您選擇的時間強制創建句柄。 這可以通過以下三種方法之一來完成:
@TnTinMn-強制創建控件。 ...任何想法會導致延遲的句柄創建嗎?
為了回答這個問題,我請您參考資料來源。
控件何時創建其句柄? (控件何時調用CreateWindowEx?)控件嘗試盡可能多地推遲創建其句柄。 這是因為設置屬性會強制CLR和user32之間進行健談互操作。
通常,所有控件的句柄都是在調用Form.Load事件之前創建的。 如果調用了“ Handle”屬性並且尚未創建該句柄,或者已調用CreateControl(),則也可以創建句柄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.