DataGridView控件用法合集(十一)
近期将DataGridView常用的一些用法做了一个整理。为防止页面过长,现分批贴出来,此为第十一部分。
DataGridView特殊控件
56. DataGridView根据值不同在另一列中显示相应图片
57. DataGridView中显示进度条(ProgressBar) 58. DataGridView中添加MaskedTextBox 56. DataGridView根据值不同在另一列中显示相应图片 57. DataGridView中显示进度条(ProgressBar) [VB.NET] Imports System Imports System.Drawing Imports System.Windows.Forms ''' <summary> ''' DataGridViewProgressBarCellオブジェクトの列 ''' </summary> Public Class DataGridViewProgressBarColumn Inherits DataGridViewTextBoxColumn 'コンストラクタ Public Sub New() Me.CellTemplate = New DataGridViewProgressBarCell() End Sub 'CellTemplateの取得と設定 Public Overrides Property CellTemplate() As DataGridViewCell Get Return MyBase.CellTemplate End Get Set(ByVal value As DataGridViewCell) 'DataGridViewProgressBarCell以外はホストしない If Not TypeOf value Is DataGridViewProgressBarCell Then Throw New InvalidCastException( _ "DataGridViewProgressBarCellオブジェクトを" + _ "指定してください。") End If MyBase.CellTemplate = value End Set End Property ''' <summary> ''' ProgressBarの最大値 ''' </summary> Public Property Maximum() As Integer Get Return CType(Me.CellTemplate,DataGridViewProgressBarCell).Maximum End Get Set(ByVal value As Integer) If Me.Maximum = value Then Return End If 'セルテンプレートの値を変更する CType(Me.CellTemplate,DataGridViewProgressBarCell).Maximum = value 'DataGridViewにすでに追加されているセルの値を変更する If Me.DataGridView Is Nothing Then Return End If Dim rowCount As Integer = Me.DataGridView.RowCount Dim i As Integer For i = 0 To rowCount - 1 Dim r As DataGridViewRow = Me.DataGridView.Rows.SharedRow(i) CType(r.Cells(Me.Index),DataGridViewProgressBarCell).Maximum = _ value Next i End Set End Property ''' <summary> ''' ProgressBarの最小値 ''' </summary> Public Property Mimimum() As Integer Get Return CType(Me.CellTemplate,DataGridViewProgressBarCell).Mimimum End Get Set(ByVal value As Integer) If Me.Mimimum = value Then Return End If 'セルテンプレートの値を変更する CType(Me.CellTemplate,DataGridViewProgressBarCell).Mimimum = value 'DataGridViewにすでに追加されているセルの値を変更する If Me.DataGridView Is Nothing Then Return End If Dim rowCount As Integer = Me.DataGridView.RowCount Dim i As Integer For i = 0 To rowCount - 1 Dim r As DataGridViewRow = Me.DataGridView.Rows.SharedRow(i) CType(r.Cells(Me.Index),DataGridViewProgressBarCell).Mimimum = _ value Next i End Set End Property End Class ''' <summary> ''' ProgressBarをDataGridViewに表示する ''' </summary> Public Class DataGridViewProgressBarCell Inherits DataGridViewTextBoxCell 'コンストラクタ Public Sub New() Me.maximumValue = 100 Me.mimimumValue = 0 End Sub Private maximumValue As Integer Public Property Maximum() As Integer Get Return Me.maximumValue End Get Set(ByVal value As Integer) Me.maximumValue = value End Set End Property Private mimimumValue As Integer Public Property Mimimum() As Integer Get Return Me.mimimumValue End Get Set(ByVal value As Integer) Me.mimimumValue = value End Set End Property 'セルの値のデータ型を指定する 'ここでは、整数型とする Public Overrides ReadOnly Property ValueType() As Type Get Return GetType(Integer) End Get End Property '新しいレコード行のセルの既定値を指定する Public Overrides ReadOnly Property DefaultNewRowValue() As Object Get Return 0 End Get End Property '新しいプロパティを追加しているため、 ' Cloneメソッドをオーバーライドする必要がある Public Overrides Function Clone() As Object Dim cell As DataGridViewProgressBarCell = _ CType(MyBase.Clone(),DataGridViewProgressBarCell) cell.Maximum = Me.Maximum cell.Mimimum = Me.Mimimum Return cell End Function Protected Overrides Sub Paint(ByVal graphics As Graphics,_ ByVal clipBounds As Rectangle,_ ByVal cellBounds As Rectangle,_ ByVal rowIndex As Integer,_ ByVal cellState As DataGridViewElementStates,_ ByVal value As Object,_ ByVal formattedValue As Object,_ ByVal errorText As String,_ ByVal cellStyle As DataGridViewCellStyle,_ ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle,_ ByVal paintParts As DataGridViewPaintParts) '値を決定する Dim intValue As Integer = 0 If TypeOf value Is Integer Then intValue = CInt(value) End If If intValue < Me.mimimumValue Then intValue = Me.mimimumValue End If If intValue > Me.maximumValue Then intValue = Me.maximumValue End If '割合を計算する Dim rate As Double = CDbl(intValue - Me.mimimumValue) / _ (Me.maximumValue - Me.mimimumValue) 'セルの境界線(枠)を描画する If (paintParts And DataGridViewPaintParts.Border) = _ DataGridViewPaintParts.Border Then Me.PaintBorder(graphics,clipBounds,cellBounds,_ cellStyle,advancedBorderStyle) End If '境界線の内側に範囲を取得する Dim borderRect As Rectangle = Me.BorderWidths(advancedBorderStyle) Dim paintRect As New Rectangle(cellBounds.Left + borderRect.Left,_ cellBounds.Top + borderRect.Top,_ cellBounds.Width - borderRect.Right,_ cellBounds.Height - borderRect.Bottom) '背景色を決定する '選択されている時とされていない時で色を変える Dim isSelected As Boolean = _ ((cellState And DataGridViewElementStates.Selected) = _ DataGridViewElementStates.Selected) Dim bkColor As Color If isSelected AndAlso _ (paintParts And DataGridViewPaintParts.SelectionBackground) = _ DataGridViewPaintParts.SelectionBackground Then bkColor = cellStyle.SelectionBackColor Else bkColor = cellStyle.BackColor End If '背景を描画する If (paintParts And DataGridViewPaintParts.Background) = _ DataGridViewPaintParts.Background Then Dim backBrush As New SolidBrush(bkColor) Try graphics.FillRectangle(backBrush,paintRect) Finally backBrush.Dispose() End Try End If 'Paddingを差し引く paintRect.Offset(cellStyle.Padding.Right,cellStyle.Padding.Top) paintRect.Width -= cellStyle.Padding.Horizontal paintRect.Height -= cellStyle.Padding.Vertical 'ProgressBarを描画する If (paintParts And DataGridViewPaintParts.ContentForeground) = _ DataGridViewPaintParts.ContentForeground Then If ProgressBarRenderer.IsSupported Then 'visualスタイルで描画する 'ProgressBarの枠を描画する ProgressBarRenderer.DrawHorizontalBar(graphics,paintRect) 'ProgressBarのバーを描画する Dim barBounds As New Rectangle(paintRect.Left + 3,_ paintRect.Top + 3,_ paintRect.Width - 4,_ paintRect.Height - 6) barBounds.Width = CInt(Math.Round((barBounds.Width * rate))) ProgressBarRenderer.DrawHorizontalChunks(graphics,barBounds) Else 'visualスタイルで描画できない時 graphics.FillRectangle(Brushes.White,paintRect) graphics.DrawRectangle(Pens.Black,paintRect) Dim barBounds As New Rectangle(paintRect.Left + 1,_ paintRect.Top + 1,_ paintRect.Width - 1,_ paintRect.Height - 1) barBounds.Width = CInt(Math.Round((barBounds.Width * rate))) graphics.FillRectangle(Brushes.Blue,barBounds) End If End If 'フォーカスの枠を表示する If Me.DataGridView.CurrentCellAddress.X = Me.ColumnIndex AndAlso _ Me.DataGridView.CurrentCellAddress.Y = Me.RowIndex AndAlso _ (paintParts And DataGridViewPaintParts.Focus) = _ DataGridViewPaintParts.Focus AndAlso _ Me.DataGridView.Focused Then 'フォーカス枠の大きさを適当に決める Dim focusRect As Rectangle = paintRect focusRect.Inflate(-3,-3) ControlPaint.DrawFocusRectangle(graphics,focusRect) '背景色を指定してフォーカス枠を描画する時 'ControlPaint.DrawFocusRectangle( ' graphics,focusRect,Color.Empty,bkColor); End If 'テキストを表示する If (paintParts And DataGridViewPaintParts.ContentForeground) = _ DataGridViewPaintParts.ContentForeground Then '表示するテキストを決定 Dim txt As String = String.Format("{0}%",Math.Round((rate * 100))) 'string txt = formattedValue.ToString(); '本来は、cellStyleによりTextFormatFlagsを決定すべき Dim flags As TextFormatFlags = _ TextFormatFlags.HorizontalCenter Or _ TextFormatFlags.VerticalCenter '色を決定 Dim fColor As Color = cellStyle.ForeColor 'if (isSelected) ' fColor = cellStyle.SelectionForeColor; 'else ' fColor = cellStyle.ForeColor; 'テキストを描画する paintRect.Inflate(-2,-2) TextRenderer.DrawText( _ graphics,txt,cellStyle.Font,paintRect,fColor,flags) End If 'エラーアイコンの表示 If (paintParts And DataGridViewPaintParts.ErrorIcon) = _ DataGridViewPaintParts.ErrorIcon AndAlso _ Me.DataGridView.ShowCellErrors AndAlso _ Not String.IsNullOrEmpty(errorText) Then 'エラーアイコンを表示させる領域を取得 Dim iconBounds As Rectangle = _ Me.GetErrorIconBounds(graphics,cellStyle,rowIndex) iconBounds.Offset(cellBounds.X,cellBounds.Y) 'エラーアイコンを描画 Me.PaintErrorIcon(graphics,iconBounds,errorText) End If End Sub End Class [C#] using System; using System.Drawing; using System.Windows.Forms; /// <summary> /// DataGridViewProgressBarCellオブジェクトの列 /// </summary> public class DataGridViewProgressBarColumn : DataGridViewTextBoxColumn { //コンストラクタ public DataGridViewProgressBarColumn() { this.CellTemplate = new DataGridViewProgressBarCell(); } //CellTemplateの取得と設定 public override DataGridViewCell CellTemplate { get { return base.CellTemplate; } set { //DataGridViewProgressBarCell以外はホストしない if (!(value is DataGridViewProgressBarCell)) { throw new InvalidCastException( "DataGridViewProgressBarCellオブジェクトを" + "指定してください。"); } base.CellTemplate = value; } } /// <summary> /// ProgressBarの最大値 /// </summary> public int Maximum { get { return ((DataGridViewProgressBarCell)this.CellTemplate).Maximum; } set { if (this.Maximum == value) return; //セルテンプレートの値を変更する ((DataGridViewProgressBarCell)this.CellTemplate).Maximum = value; //DataGridViewにすでに追加されているセルの値を変更する if (this.DataGridView == null) return; int rowCount = this.DataGridView.RowCount; for (int i = 0; i < rowCount; i++) { DataGridViewRow r = this.DataGridView.Rows.SharedRow(i); ((DataGridViewProgressBarCell)r.Cells[this.Index]).Maximum = value; } } } /// <summary> /// ProgressBarの最小値 /// </summary> public int Mimimum { get { return ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum; } set { if (this.Mimimum == value) return; //セルテンプレートの値を変更する ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum = value; //DataGridViewにすでに追加されているセルの値を変更する if (this.DataGridView == null) return; int rowCount = this.DataGridView.RowCount; for (int i = 0; i < rowCount; i++) { DataGridViewRow r = this.DataGridView.Rows.SharedRow(i); ((DataGridViewProgressBarCell)r.Cells[this.Index]).Mimimum = value; } } } } /// <summary> /// ProgressBarをDataGridViewに表示する /// </summary> public class DataGridViewProgressBarCell : DataGridViewTextBoxCell { //コンストラクタ public DataGridViewProgressBarCell() { this.maximumValue = 100; this.mimimumValue = 0; } private int maximumValue; public int Maximum { get { return this.maximumValue; } set { this.maximumValue = value; } } private int mimimumValue; public int Mimimum { get { return this.mimimumValue; } set { this.mimimumValue = value; } } //セルの値のデータ型を指定する //ここでは、整数型とする public override Type ValueType { get { return typeof(int); } } //新しいレコード行のセルの既定値を指定する public override object DefaultNewRowValue { get { return 0; } } //新しいプロパティを追加しているため、 // Cloneメソッドをオーバーライドする必要がある public override object Clone() { DataGridViewProgressBarCell cell = (DataGridViewProgressBarCell)base.Clone(); cell.Maximum = this.Maximum; cell.Mimimum = this.Mimimum; return cell; } protected override void Paint(Graphics graphics, Rectangle clipBounds,Rectangle cellBounds, int rowIndex,DataGridViewElementStates cellState, object value,object formattedValue,string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { //値を決定する int intValue = 0; if (value is int) intValue = (int)value; if (intValue < this.mimimumValue) intValue = this.mimimumValue; if (intValue > this.maximumValue) intValue = this.maximumValue; //割合を計算する double rate = (double)(intValue - this.mimimumValue) / (this.maximumValue - this.mimimumValue); //セルの境界線(枠)を描画する if ((paintParts & DataGridViewPaintParts.Border) == DataGridViewPaintParts.Border) { this.PaintBorder(graphics, cellStyle,advancedBorderStyle); } //境界線の内側に範囲を取得する Rectangle borderRect = this.BorderWidths(advancedBorderStyle); Rectangle paintRect = new Rectangle( cellBounds.Left + borderRect.Left, cellBounds.Top + borderRect.Top, cellBounds.Width - borderRect.Right, cellBounds.Height - borderRect.Bottom); //背景色を決定する //選択されている時とされていない時で色を変える bool isSelected = (cellState & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected; Color bkColor; if (isSelected && (paintParts & DataGridViewPaintParts.SelectionBackground) == DataGridViewPaintParts.SelectionBackground) { bkColor = cellStyle.SelectionBackColor; } else { bkColor = cellStyle.BackColor; } //背景を描画する if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background) { using (SolidBrush backBrush = new SolidBrush(bkColor)) { graphics.FillRectangle(backBrush,paintRect); } } //Paddingを差し引く paintRect.Offset(cellStyle.Padding.Right,cellStyle.Padding.Top); paintRect.Width -= cellStyle.Padding.Horizontal; paintRect.Height -= cellStyle.Padding.Vertical; //ProgressBarを描画する if ((paintParts & DataGridViewPaintParts.ContentForeground) == DataGridViewPaintParts.ContentForeground) { if (ProgressBarRenderer.IsSupported) { //visualスタイルで描画する //ProgressBarの枠を描画する ProgressBarRenderer.DrawHorizontalBar(graphics,paintRect); //ProgressBarのバーを描画する Rectangle barBounds = new Rectangle( paintRect.Left + 3,paintRect.Top + 3, paintRect.Width - 4,paintRect.Height - 6); barBounds.Width = (int)Math.Round(barBounds.Width * rate); ProgressBarRenderer.DrawHorizontalChunks(graphics,barBounds); } else { //visualスタイルで描画できない時 graphics.FillRectangle(Brushes.White,paintRect); graphics.DrawRectangle(Pens.Black,paintRect); Rectangle barBounds = new Rectangle( paintRect.Left + 1,paintRect.Top + 1, paintRect.Width - 1,paintRect.Height - 1); barBounds.Width = (int)Math.Round(barBounds.Width * rate); graphics.FillRectangle(Brushes.Blue,barBounds); } } //フォーカスの枠を表示する if (this.DataGridView.CurrentCellAddress.X == this.ColumnIndex && this.DataGridView.CurrentCellAddress.Y == this.RowIndex && (paintParts & DataGridViewPaintParts.Focus) == DataGridViewPaintParts.Focus && this.DataGridView.Focused) { //フォーカス枠の大きさを適当に決める Rectangle focusRect = paintRect; focusRect.Inflate(-3,-3); ControlPaint.DrawFocusRectangle(graphics,focusRect); //背景色を指定してフォーカス枠を描画する時 //ControlPaint.DrawFocusRectangle( // graphics,bkColor); } //テキストを表示する if ((paintParts & DataGridViewPaintParts.ContentForeground) == DataGridViewPaintParts.ContentForeground) { //表示するテキストを決定 string txt = string.Format("{0}%",Math.Round(rate * 100)); //string txt = formattedValue.ToString(); //本来は、cellStyleによりTextFormatFlagsを決定すべき TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter; //色を決定 Color fColor = cellStyle.ForeColor; //if (isSelected) // fColor = cellStyle.SelectionForeColor; //else // fColor = cellStyle.ForeColor; //テキストを描画する paintRect.Inflate(-2,-2); TextRenderer.DrawText(graphics, paintRect,flags); } //エラーアイコンの表示 if ((paintParts & DataGridViewPaintParts.ErrorIcon) == DataGridViewPaintParts.ErrorIcon && this.DataGridView.ShowCellErrors && !string.IsNullOrEmpty(errorText)) { //エラーアイコンを表示させる領域を取得 Rectangle iconBounds = this.GetErrorIconBounds( graphics,rowIndex); iconBounds.Offset(cellBounds.X,cellBounds.Y); //エラーアイコンを描画 this.PaintErrorIcon(graphics,errorText); } } } 用法如下 [VB.NET] 'DataGridViewProgressBarColumnを作成する Dim pbColumn As New DataGridViewProgressBarColumn() 'データソースの"Column1"をバインドする pbColumn.DataPropertyName = "Column1" '列を追加する DataGridView1.Columns.Add(pbColumn) [C#] //DataGridViewProgressBarColumnを作成する DataGridViewProgressBarColumn pbColumn = new DataGridViewProgressBarColumn(); //データソースの"Column1"をバインドする pbColumn.DataPropertyName = "Column1"; //列を追加する DataGridView1.Columns.Add(pbColumn); 58. DataGridView中添加MaskedTextBox [VB.NET] Imports System Imports System.Windows.Forms ''' <summary> ''' DataGridViewMaskedTextBoxCellオブジェクトの列を表します。 ''' </summary> Public Class DataGridViewMaskedTextBoxColumn Inherits DataGridViewColumn 'CellTemplateとするDataGridViewMaskedTextBoxCellオブジェクトを指定して '基本クラスのコンストラクタを呼び出す Public Sub New() MyBase.New(New DataGridViewMaskedTextBoxCell()) End Sub Private maskValue As String = "" ''' <summary> ''' MaskedTextBoxのMaskプロパティに適用する値 ''' </summary> Public Property Mask() As String Get Return Me.maskValue End Get Set(ByVal value As String) Me.maskValue = value End Set End Property '新しいプロパティを追加しているため、 ' Cloneメソッドをオーバーライドする必要がある Public Overrides Function Clone() As Object Dim col As DataGridViewMaskedTextBoxColumn = _ CType(MyBase.Clone(),DataGridViewMaskedTextBoxColumn) col.Mask = Me.Mask Return col End Function 'CellTemplateの取得と設定 Public Overrides Property CellTemplate() As DataGridViewCell Get Return MyBase.CellTemplate End Get Set(ByVal value As DataGridViewCell) 'DataGridViewMaskedTextBoxCellしか ' CellTemplateに設定できないようにする If Not TypeOf value Is DataGridViewMaskedTextBoxCell Then Throw New InvalidCastException( _ "DataGridViewMaskedTextBoxCellオブジェクトを" + _ "指定してください。") End If MyBase.CellTemplate = value End Set End Property End Class ''' <summary> ''' MaskedTextBoxで編集できるテキスト情報を ''' DataGridViewコントロールに表示します。 ''' </summary> Public Class DataGridViewMaskedTextBoxCell Inherits DataGridViewTextBoxCell 'コンストラクタ Public Sub New() End Sub '編集コントロールを初期化する '編集コントロールは別のセルや列でも使いまわされるため、初期化の必要がある Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer,_ ByVal initialFormattedValue As Object,_ ByVal dataGridViewCellStyle As DataGridViewCellStyle) MyBase.InitializeEditingControl(rowIndex,initialFormattedValue,_ dataGridViewCellStyle) '編集コントロールの取得 Dim maskedBox As DataGridViewMaskedTextBoxEditingControl = _ Me.DataGridView.EditingControl If Not (maskedBox Is Nothing) Then 'Textを設定 maskedBox.Text = IIf(Me.Value Is Nothing,"",Me.Value.ToString()) 'カスタム列のプロパティを反映させる Dim column As DataGridViewMaskedTextBoxColumn = Me.OwningColumn If Not (column Is Nothing) Then maskedBox.Mask = column.Mask End If End If End Sub '編集コントロールの型を指定する Public Overrides ReadOnly Property EditType() As Type Get Return GetType(DataGridViewMaskedTextBoxEditingControl) End Get End Property 'セルの値のデータ型を指定する 'ここでは、Object型とする '基本クラスと同じなので、オーバーライドの必要なし Public Overrides ReadOnly Property ValueType() As Type Get Return GetType(Object) End Get End Property '新しいレコード行のセルの既定値を指定する Public Overrides ReadOnly Property DefaultNewRowValue() As Object Get Return MyBase.DefaultNewRowValue End Get End Property End Class ''' <summary> ''' DataGridViewMaskedTextBoxCellでホストされる ''' MaskedTextBoxコントロールを表します。 ''' </summary> Public Class DataGridViewMaskedTextBoxEditingControl Inherits MaskedTextBox Implements IDataGridViewEditingControl '編集コントロールが表示されているDataGridView Private dataGridView As DataGridView '編集コントロールが表示されている行 Private rowIndex As Integer '編集コントロールの値とセルの値が違うかどうか Private valueChanged As Boolean 'コンストラクタ Public Sub New() Me.TabStop = False End Sub '編集コントロールで変更されたセルの値 Public Function GetEditingControlFormattedValue( _ ByVal context As DataGridViewDataErrorContexts) As Object _ Implements IDataGridViewEditingControl.GetEditingControlFormattedValue Return Me.Text End Function '編集コントロールで変更されたセルの値 Public Property EditingControlFormattedValue() As Object _ Implements IDataGridViewEditingControl.EditingControlFormattedValue Get Return Me.GetEditingControlFormattedValue( _ DataGridViewDataErrorContexts.Formatting) End Get Set(ByVal value As Object) Me.Text = CStr(value) End Set End Property 'セルスタイルを編集コントロールに適用する '編集コントロールの前景色、背景色、フォントなどをセルスタイルに合わせる Public Sub ApplyCellStyleToEditingControl( _ ByVal dataGridViewCellStyle As DataGridViewCellStyle) _ Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl Me.Font = dataGridViewCellStyle.Font Me.ForeColor = dataGridViewCellStyle.ForeColor Me.BackColor = dataGridViewCellStyle.BackColor Select Case dataGridViewCellStyle.Alignment Case DataGridViewContentAlignment.BottomCenter,_ DataGridViewContentAlignment.MiddleCenter,_ DataGridViewContentAlignment.TopCenter Me.TextAlign = HorizontalAlignment.Center Case DataGridViewContentAlignment.BottomRight,_ DataGridViewContentAlignment.MiddleRight,_ DataGridViewContentAlignment.TopRight Me.TextAlign = HorizontalAlignment.Right Case Else Me.TextAlign = HorizontalAlignment.Left End Select End Sub '編集するセルがあるDataGridView Public Property EditingControlDataGridView() As DataGridView _ Implements IDataGridViewEditingControl.EditingControlDataGridView Get Return Me.dataGridView End Get Set(ByVal value As DataGridView) Me.dataGridView = value End Set End Property '編集している行のインデックス Public Property EditingControlRowIndex() As Integer _ Implements IDataGridViewEditingControl.EditingControlRowIndex Get Return Me.rowIndex End Get Set(ByVal value As Integer) Me.rowIndex = value End Set End Property '値が変更されたかどうか '編集コントロールの値とセルの値が違うかどうか Public Property EditingControlValueChanged() As Boolean _ Implements IDataGridViewEditingControl.EditingControlValueChanged Get Return Me.valueChanged End Get Set(ByVal value As Boolean) Me.valueChanged = value End Set End Property '指定されたキーをDataGridViewが処理するか、編集コントロールが処理するか 'Trueを返すと、編集コントロールが処理する 'dataGridViewWantsInputKeyがTrueの時は、DataGridViewが処理できる Public Function EditingControlWantsInputKey(ByVal keyData As Keys,_ ByVal dataGridViewWantsInputKey As Boolean) As Boolean _ Implements IDataGridViewEditingControl.EditingControlWantsInputKey 'Keys.Left、Right、Home、Endの時は、Trueを返す 'このようにしないと、これらのキーで別のセルにフォーカスが移ってしまう Select Case keyData And Keys.KeyCode Case Keys.Right,Keys.End,Keys.Left,Keys.Home Return True Case Else Return False End Select End Function 'マウスカーソルがEditingPanel上にあるときのカーソルを指定する 'EditingPanelは編集コントロールをホストするパネルで、 '編集コントロールがセルより小さいとコントロール以外の部分がパネルとなる Public ReadOnly Property EditingPanelCursor() As Cursor _ Implements IDataGridViewEditingControl.EditingPanelCursor Get Return MyBase.Cursor End Get End Property 'コントロールで編集する準備をする 'テキストを選択状態にしたり、挿入ポインタを末尾にしたりする Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _ Implements IDataGridViewEditingControl.PrepareEditingControlForEdit If selectAll Then '選択状態にする Me.SelectAll() Else '挿入ポインタを末尾にする Me.SelectionStart = Me.TextLength End If End Sub '値が変更した時に、セルの位置を変更するかどうか '値が変更された時に編集コントロールの大きさが変更される時はTrue Public ReadOnly Property RepositionEditingControlOnValueChange() _ As Boolean _ Implements _ IDataGridViewEditingControl.RepositionEditingControlOnValueChange Get Return False End Get End Property '値が変更された時 Protected Overrides Sub OnTextChanged(ByVal e As EventArgs) MyBase.OnTextChanged(e) '値が変更されたことをDataGridViewに通知する Me.valueChanged = True Me.dataGridView.NotifyCurrentCellDirty(True) End Sub End Class [C#] using System; using System.Windows.Forms; /// <summary> /// DataGridViewMaskedTextBoxCellオブジェクトの列を表します。 /// </summary> public class DataGridViewMaskedTextBoxColumn : DataGridViewColumn { //CellTemplateとするDataGridViewMaskedTextBoxCellオブジェクトを指定して //基本クラスのコンストラクタを呼び出す public DataGridViewMaskedTextBoxColumn() : base(new DataGridViewMaskedTextBoxCell()) { } private string maskValue = ""; /// <summary> /// MaskedTextBoxのMaskプロパティに適用する値 /// </summary> public string Mask { get { return this.maskValue; } set { this.maskValue = value; } } //新しいプロパティを追加しているため、 // Cloneメソッドをオーバーライドする必要がある public override object Clone() { DataGridViewMaskedTextBoxColumn col = (DataGridViewMaskedTextBoxColumn)base.Clone(); col.Mask = this.Mask; return col; } //CellTemplateの取得と設定 public override DataGridViewCell CellTemplate { get { return base.CellTemplate; } set { //DataGridViewMaskedTextBoxCellしか // CellTemplateに設定できないようにする if (!(value is DataGridViewMaskedTextBoxCell)) { throw new InvalidCastException( "DataGridViewMaskedTextBoxCellオブジェクトを" + "指定してください。"); } base.CellTemplate = value; } } } /// <summary> /// MaskedTextBoxで編集できるテキスト情報を /// DataGridViewコントロールに表示します。 /// </summary> public class DataGridViewMaskedTextBoxCell : DataGridViewTextBoxCell { //コンストラクタ public DataGridViewMaskedTextBoxCell() { } //編集コントロールを初期化する //編集コントロールは別のセルや列でも使いまわされるため、初期化の必要がある public override void InitializeEditingControl( int rowIndex,object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { base.InitializeEditingControl(rowIndex, initialFormattedValue,dataGridViewCellStyle); //編集コントロールの取得 DataGridViewMaskedTextBoxEditingControl maskedBox = this.DataGridView.EditingControl as DataGridViewMaskedTextBoxEditingControl; if (maskedBox != null) { //Textを設定 maskedBox.Text = this.Value != null ? this.Value.ToString() : ""; //カスタム列のプロパティを反映させる DataGridViewMaskedTextBoxColumn column = this.OwningColumn as DataGridViewMaskedTextBoxColumn; if (column != null) { maskedBox.Mask = column.Mask; } } } //編集コントロールの型を指定する public override Type EditType { get { return typeof(DataGridViewMaskedTextBoxEditingControl); } } //セルの値のデータ型を指定する //ここでは、Object型とする //基本クラスと同じなので、オーバーライドの必要なし public override Type ValueType { get { return typeof(object); } } //新しいレコード行のセルの既定値を指定する public override object DefaultNewRowValue { get { return base.DefaultNewRowValue; } } } /// <summary> /// DataGridViewMaskedTextBoxCellでホストされる /// MaskedTextBoxコントロールを表します。 /// </summary> public class DataGridViewMaskedTextBoxEditingControl : MaskedTextBox,IDataGridViewEditingControl { //編集コントロールが表示されているDataGridView DataGridView dataGridView; //編集コントロールが表示されている行 int rowIndex; //編集コントロールの値とセルの値が違うかどうか bool valueChanged; //コンストラクタ public DataGridViewMaskedTextBoxEditingControl() { this.TabStop = false; } #region IDataGridViewEditingControl メンバ //編集コントロールで変更されたセルの値 public object GetEditingControlFormattedValue( DataGridViewDataErrorContexts context) { return this.Text; } //編集コントロールで変更されたセルの値 public object EditingControlFormattedValue { get { return this.GetEditingControlFormattedValue( DataGridViewDataErrorContexts.Formatting); } set { this.Text = (string)value; } } //セルスタイルを編集コントロールに適用する //編集コントロールの前景色、背景色、フォントなどをセルスタイルに合わせる public void ApplyCellStyleToEditingControl( DataGridViewCellStyle dataGridViewCellStyle) { this.Font = dataGridViewCellStyle.Font; this.ForeColor = dataGridViewCellStyle.ForeColor; this.BackColor = dataGridViewCellStyle.BackColor; switch (dataGridViewCellStyle.Alignment) { case DataGridViewContentAlignment.BottomCenter: case DataGridViewContentAlignment.MiddleCenter: case DataGridViewContentAlignment.TopCenter: this.TextAlign = HorizontalAlignment.Center; break; case DataGridViewContentAlignment.BottomRight: case DataGridViewContentAlignment.MiddleRight: case DataGridViewContentAlignment.TopRight: this.TextAlign = HorizontalAlignment.Right; break; default: this.TextAlign = HorizontalAlignment.Left; break; } } //編集するセルがあるDataGridView public DataGridView EditingControlDataGridView { get { return this.dataGridView; } set { this.dataGridView = value; } } //編集している行のインデックス public int EditingControlRowIndex { get { return this.rowIndex; } set { this.rowIndex = value; } } //値が変更されたかどうか //編集コントロールの値とセルの値が違うかどうか public bool EditingControlValueChanged { get { return this.valueChanged; } set { this.valueChanged = value; } } //指定されたキーをDataGridViewが処理するか、編集コントロールが処理するか //Trueを返すと、編集コントロールが処理する //dataGridViewWantsInputKeyがTrueの時は、DataGridViewが処理できる public bool EditingControlWantsInputKey( Keys keyData,bool dataGridViewWantsInputKey) { //Keys.Left、Right、Home、Endの時は、Trueを返す //このようにしないと、これらのキーで別のセルにフォーカスが移ってしまう switch (keyData & Keys.KeyCode) { case Keys.Right: case Keys.End: case Keys.Left: case Keys.Home: return true; default: return false; } } //マウスカーソルがEditingPanel上にあるときのカーソルを指定する //EditingPanelは編集コントロールをホストするパネルで、 //編集コントロールがセルより小さいとコントロール以外の部分がパネルとなる public Cursor EditingPanelCursor { get { return base.Cursor; } } //コントロールで編集する準備をする //テキストを選択状態にしたり、挿入ポインタを末尾にしたりする public void PrepareEditingControlForEdit(bool selectAll) { if (selectAll) { //選択状態にする this.SelectAll(); } else { //挿入ポインタを末尾にする this.SelectionStart = this.TextLength; } } //値が変更した時に、セルの位置を変更するかどうか //値が変更された時に編集コントロールの大きさが変更される時はTrue public bool RepositionEditingControlOnValueChange { get { return false; } } #endregion //値が変更された時 protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); //値が変更されたことをDataGridViewに通知する this.valueChanged = true; this.dataGridView.NotifyCurrentCellDirty(true); } } 用法如下 [VB.NET] 'DataGridViewMaskedTextBoxColumnを作成 Dim maskedColumn As New DataGridViewMaskedTextBoxColumn() 'データソースの"Column1"をバインドする maskedColumn.DataPropertyName = "Column1" 'MaskedTextBoxのMaskプロパティとなる値を設定する maskedColumn.Mask = "000" 'DataGridViewに列を追加する DataGridView1.Columns.Add(maskedColumn) [C#] //DataGridViewMaskedTextBoxColumnを作成 DataGridViewMaskedTextBoxColumn maskedColumn = new DataGridViewMaskedTextBoxColumn(); //データソースの"Column1"をバインドする maskedColumn.DataPropertyName = "Column1"; //MaskedTextBoxのMaskプロパティとなる値を設定する maskedColumn.Mask = "000"; //DataGridViewに列を追加する DataGridView1.Columns.Add(maskedColumn); [VB.NET] ''' <summary> ''' セルの値により、適当なアイコンを表示する ''' </summary> Public Class DataGridViewErrorIconColumn Inherits DataGridViewImageColumn Public Sub New() Me.CellTemplate = New DataGridViewErrorIconCell() Me.ValueType = Me.CellTemplate.ValueType End Sub End Class ''' <summary> ''' セルの値により、適当なアイコンを表示する ''' </summary> Public Class DataGridViewErrorIconCell Inherits DataGridViewImageCell Public Sub New() Me.ValueType = GetType(Integer) End Sub Protected Overrides Function GetFormattedValue( _ ByVal value As Object,ByVal rowIndex As Integer,_ ByRef cellStyle As DataGridViewCellStyle,_ ByVal valueTypeConverter As System.ComponentModel.TypeConverter,_ ByVal formattedValueTypeConverter As System.ComponentModel.TypeConverter,_ ByVal context As DataGridViewDataErrorContexts) As Object '値が0の時は情報、1の時は警告、2の時はエラーアイコンを表示する Select Case CInt(value) Case 1 Return SystemIcons.Information Case 2 Return SystemIcons.Warning Case 3 Return SystemIcons.Error Case Else Return Nothing End Select End Function Public Overrides ReadOnly Property DefaultNewRowValue() As Object Get Return 0 End Get End Property End Class [C#] using System; using System.ComponentModel; using System.Windows.Forms; /// <summary> /// セルの値により、適当なアイコンを表示する /// </summary> public class DataGridViewErrorIconColumn : DataGridViewImageColumn { public DataGridViewErrorIconColumn() { this.CellTemplate = new DataGridViewErrorIconCell(); this.ValueType = this.CellTemplate.ValueType; } } /// <summary> /// セルの値により、適当なアイコンを表示する /// </summary> public class DataGridViewErrorIconCell : DataGridViewImageCell { public DataGridViewErrorIconCell() { this.ValueType = typeof(int); } protected override object GetFormattedValue( object value,int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { //値が0の時は情報、1の時は警告、2の時はエラーアイコンを表示する switch ((int)value) { case 1: return SystemIcons.Information; case 2: return SystemIcons.Warning; case 3: return SystemIcons.Error; default: return null; } } public override object DefaultNewRowValue { get { return 0; } } } 用法如下 [VB.NET] 'DataGridViewErrorIconColumnを作成 Dim iconColumn As New DataGridViewErrorIconColumn() 'Column1列(整数型)をバインドする iconColumn.DataPropertyName = "Column1" 'DataGridViewに追加 DataGridView1.Columns.Add(iconColumn) [C#] //DataGridViewErrorIconColumnを作成 DataGridViewErrorIconColumn iconColumn = new DataGridViewErrorIconColumn(); //Column1列(整数型)をバインドする iconColumn.DataPropertyName = "Column1"; //DataGridViewに追加 DataGridView1.Columns.Add(iconColumn); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |