2011-07-19 141 views
2

我想創建一個自定義的DataGridViewRow作爲分隔符(將數據分成組)。我做到了通過重寫的DataGridViewRow類的PainCells方法是這樣的:自定義DataGridViewRow問題

protected override void PaintCells(Graphics graphics, Rectangle clipBounds, Rectangle rowBounds, int rowIndex, DataGridViewElementStates rowState, bool isFirstDisplayedRow, bool isLastVisibleRow, DataGridViewPaintParts paintParts) 
    { 
     graphics.FillRectangle(new SolidBrush(BackgroundColor),rowBounds); 

     StringFormat format = new StringFormat {Alignment = StringAlignment.Center,LineAlignment = StringAlignment.Center}; 
     graphics.DrawString(Text, this.DataGridView.Font, new SolidBrush(ForeColor), rowBounds,format); 
    } 

凡文字,BACKGROUNDCOLOR和前景色是我SeparatorDataGridViewRow類的屬性。這些排看起來完全像我想要的那樣。但是這只是「覆蓋」,因爲在繪製的矩形下面仍然有原始的datagrid單元格。特別是與我添加的刪除按鈕形式DataGridViewButtonColumn單元格。因爲如果我點擊按鈕是我的分隔符行被刪除的單元格。

我不認爲這是達到我要存檔的正確方法,所以我會很高興如果你們可以向我展示正確的方向或告訴我可以用這種解決方案做什麼來阻止用戶可能性做無論什麼是「在繪製的rectagle下面」的任何東西。

我幾乎沒有創建自定義控件的經驗,所以我不知道要重寫什麼方法或要添加什麼來實現特定目標。 每個幫助讚賞:)

+0

有什麼辦法可以告訴DataGridView不要在給定的行中繪製單元格。或者在給定類型的行中?我找不到任何方法對此負責。 DataGridView的onPaint方法只給出了ClipRectangle和Graphics作爲參數,所以我不能確定他正在繪製哪一行。 – Brazol

回答

0

好吧,我部分解決了我的問題。我不知道這個解決方案是否好,它帶來了另一個對我來說很神祕的問題。

在我的SeparatorDataGridViewRow上,我將Tag設置爲「Separator」。然後,我創建了我重寫OnUserDeletingRow方法我自己的DataGridView控制:

protected override void OnUserDeletingRow(DataGridViewRowCancelEventArgs e) 
    { 
     if (e.Row.Tag != null && e.Row.Tag.ToString().Equals("Separator")) 
     { 
      e.Cancel = true; 
      return; 
     } 
     base.OnUserDeletingRow(e); 
    } 

這樣我行分隔符不能被用戶刪除。但現在發生了奇怪的事情。我有這樣一個DataGridView:

enter image description here

當我選擇名稱爲「2」的行刪除了它的一切工作正常:

enter image description here

它包含所有行的作品。但如果我選擇任何分隔行,並按下Delete鍵也不會被刪除,但如果我再刪除任何行它上面發生這種情況:

enter image description here

在這種情況下,我選擇了分離器2,然後刪除行名爲「2」。這很奇怪,因爲實際的行被刪除,而選定的行實際上是Separator2行。這是某種油漆問題。但我不知道爲什麼只有當我「嘗試」刪除分隔行之前發生這種情況。在刪除上述任何內容之前嘗試刪除Separator行時,繪畫過程中發生了哪些變化?