DataGridView用法合集(11):特殊控件

目录

56. DataGridView根据值不同在另一列中显示相应图片

57. DataGridView中显示进度条(ProgressBar)

58. DataGridView中添加MaskedTextBox

56. DataGridView根据值不同在另一列中显示相应图片

57. DataGridView中显示进度条(ProgressBar)

[VB.NET]

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class DataGridViewProgressBarColumn
    Inherits DataGridViewTextBoxColumn
    Public Sub New()
        Me.CellTemplate = New DataGridViewProgressBarCell()
    End Sub
    Public Overrides Property CellTemplate() As DataGridViewCell
        Get
            Return MyBase.CellTemplate
        End Get
        Set(ByVal value As DataGridViewCell)
            If Not TypeOf value Is DataGridViewProgressBarCell Then
                Throw New InvalidCastException( _
                    "DataGridViewProgressBarCellオブジェクトを" + _
                    "指定してください。")
            End If
            MyBase.CellTemplate = value
        End Set
    End Property

    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
            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

    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
            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

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

    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
        paintRect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top)
        paintRect.Width -= cellStyle.Padding.Horizontal
        paintRect.Height -= cellStyle.Padding.Vertical
        If (paintParts And DataGridViewPaintParts.ContentForeground) = _
            DataGridViewPaintParts.ContentForeground Then
            If ProgressBarRenderer.IsSupported Then
                ProgressBarRenderer.DrawHorizontalBar(graphics, paintRect)
                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
                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)
        End If
        If (paintParts And DataGridViewPaintParts.ContentForeground) = _
            DataGridViewPaintParts.ContentForeground Then
            Dim txt As String = String.Format("{0}%", Math.Round((rate * 100)))
            Dim flags As TextFormatFlags = _
                TextFormatFlags.HorizontalCenter Or _
                    TextFormatFlags.VerticalCenter
            Dim fColor As Color = 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, cellBounds, errorText)
        End If
    End Sub
End Class

[C#]

using System;
using System.Drawing;
using System.Windows.Forms;

public class DataGridViewProgressBarColumn : DataGridViewTextBoxColumn
{
    public DataGridViewProgressBarColumn()
    {
        this.CellTemplate = new DataGridViewProgressBarCell();
    }
    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            if (!(value is DataGridViewProgressBarCell))
            {
                throw new InvalidCastException(
                    "DataGridViewProgressBarCellオブジェクトを" +
                    "指定してください。");
            }
            base.CellTemplate = value;
        }
    }

    public int Maximum
    {
        get
        {
            return ((DataGridViewProgressBarCell)this.CellTemplate).Maximum;
        }
        set
        {
            if (this.Maximum == value)
                return;
            ((DataGridViewProgressBarCell)this.CellTemplate).Maximum =
                value;
            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;
            }
        }
    }
    public int Mimimum
    {
        get
        {
            return ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum;
        }
        set
        {
            if (this.Mimimum == value)
                return;
            ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum =
                value;
            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;
            }
        }
    }
}

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;
        }
    }
    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, clipBounds, cellBounds,
                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);
            }
        }
        paintRect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
        paintRect.Width -= cellStyle.Padding.Horizontal;
        paintRect.Height -= cellStyle.Padding.Vertical;
        if ((paintParts & DataGridViewPaintParts.ContentForeground) ==
            DataGridViewPaintParts.ContentForeground)
        {
            if (ProgressBarRenderer.IsSupported)
            {
                ProgressBarRenderer.DrawHorizontalBar(graphics, paintRect);
                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
            {
                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);
        }
        if ((paintParts & DataGridViewPaintParts.ContentForeground) ==
            DataGridViewPaintParts.ContentForeground)
        {
            string txt = string.Format("{0}%", Math.Round(rate * 100));
            TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
                TextFormatFlags.VerticalCenter;
            Color fColor = cellStyle.ForeColor;
            paintRect.Inflate(-2, -2);
            TextRenderer.DrawText(graphics, txt, cellStyle.Font,
                paintRect, fColor, flags);
        }
        if ((paintParts & DataGridViewPaintParts.ErrorIcon) ==
            DataGridViewPaintParts.ErrorIcon &&
            this.DataGridView.ShowCellErrors &&
            !string.IsNullOrEmpty(errorText))
        {
            Rectangle iconBounds = this.GetErrorIconBounds(
                graphics, cellStyle, rowIndex);
            iconBounds.Offset(cellBounds.X, cellBounds.Y);
            this.PaintErrorIcon(graphics, iconBounds, cellBounds, errorText);
        }
    }
}

用法如下

[VB.NET]

Dim pbColumn As New DataGridViewProgressBarColumn()

pbColumn.DataPropertyName = "Column1"

DataGridView1.Columns.Add(pbColumn)

[C#]

DataGridViewProgressBarColumn pbColumn =

    new DataGridViewProgressBarColumn();

pbColumn.DataPropertyName = "Column1";

DataGridView1.Columns.Add(pbColumn);

58. DataGridView中添加MaskedTextBox

[VB.NET]

Imports System
Imports System.Windows.Forms
Public Class DataGridViewMaskedTextBoxColumn
    Inherits DataGridViewColumn
    Public Sub New()
        MyBase.New(New DataGridViewMaskedTextBoxCell())
    End Sub
    Private maskValue As String = ""
    Public Property Mask() As String
        Get
            Return Me.maskValue
        End Get
        Set(ByVal value As String)
            Me.maskValue = value
        End Set
    End Property
    Public Overrides Function Clone() As Object
        Dim col As DataGridViewMaskedTextBoxColumn = _
            CType(MyBase.Clone(), DataGridViewMaskedTextBoxColumn)
        col.Mask = Me.Mask
        Return col
    End Function
    Public Overrides Property CellTemplate() As DataGridViewCell
        Get
            Return MyBase.CellTemplate
        End Get
        Set(ByVal value As DataGridViewCell)
            If Not TypeOf value Is DataGridViewMaskedTextBoxCell Then
                Throw New InvalidCastException( _
                    "DataGridViewMaskedTextBoxCellオブジェクトを" + _
                    "指定してください。")
            End If
            MyBase.CellTemplate = value
        End Set
    End Property
End Class
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
            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
    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
Public Class DataGridViewMaskedTextBoxEditingControl
    Inherits MaskedTextBox
    Implements IDataGridViewEditingControl
    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
    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
    Public Function EditingControlWantsInputKey(ByVal keyData As Keys, _
        ByVal dataGridViewWantsInputKey As Boolean) As Boolean _
        Implements IDataGridViewEditingControl.EditingControlWantsInputKey
        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

    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
    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)
        Me.valueChanged = True
        Me.dataGridView.NotifyCurrentCellDirty(True)
    End Sub
End Class

[C#]

using System;
using System.Windows.Forms;

public class DataGridViewMaskedTextBoxColumn :
    DataGridViewColumn
{
    public DataGridViewMaskedTextBoxColumn()
        : base(new DataGridViewMaskedTextBoxCell())
    {
    }
    private string maskValue = "";

    public string Mask
    {
        get
        {
            return this.maskValue;
        }
        set
        {
            this.maskValue = value;
        }
    }

    public override object Clone()
    {
        DataGridViewMaskedTextBoxColumn col =
            (DataGridViewMaskedTextBoxColumn)base.Clone();
        col.Mask = this.Mask;
        return col;
    }
    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            if (!(value is DataGridViewMaskedTextBoxCell))
            {
                throw new InvalidCastException(
                    "DataGridViewMaskedTextBoxCellオブジェクトを" +
                    "指定してください。");
            }
            base.CellTemplate = value;
        }
    }
}

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)
        {
            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);
        }
    }
    public override Type ValueType
    {
        get
        {
            return typeof(object);
        }
    }
    public override object DefaultNewRowValue
    {
        get
        {
            return base.DefaultNewRowValue;
        }
    }
}

public class DataGridViewMaskedTextBoxEditingControl :
    MaskedTextBox, IDataGridViewEditingControl
{
    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;
        }
    }
    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;
        }
    }
    public bool EditingControlWantsInputKey(
        Keys keyData, bool dataGridViewWantsInputKey)
    {
        switch (keyData & Keys.KeyCode)
        {
            case Keys.Right:
            case Keys.End:
            case Keys.Left:
            case Keys.Home:
                return true;
            default:
                return false;
        }
    }
    public Cursor EditingPanelCursor
    {
        get
        {
            return base.Cursor;
        }
    }
    public void PrepareEditingControlForEdit(bool selectAll)
    {
        if (selectAll)
        {
            this.SelectAll();
        }
        else
        {
            this.SelectionStart = this.TextLength;
        }
    }
    public bool RepositionEditingControlOnValueChange
    {
        get
        {
            return false;
        }
    }
    #endregion
    protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);
        this.valueChanged = true;
        this.dataGridView.NotifyCurrentCellDirty(true);
    }
}

用法如下

[VB.NET]

Dim maskedColumn As New DataGridViewMaskedTextBoxColumn()

maskedColumn.DataPropertyName = "Column1"

maskedColumn.Mask = "000"

DataGridView1.Columns.Add(maskedColumn)

[C#]

DataGridViewMaskedTextBoxColumn maskedColumn =

    new DataGridViewMaskedTextBoxColumn();

maskedColumn.DataPropertyName = "Column1";

maskedColumn.Mask = "000";

DataGridView1.Columns.Add(maskedColumn);

[VB.NET]

Public Class DataGridViewErrorIconColumn
    Inherits DataGridViewImageColumn
    Public Sub New()
        Me.CellTemplate = New DataGridViewErrorIconCell()
        Me.ValueType = Me.CellTemplate.ValueType
    End Sub
End Class

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
        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;

public class DataGridViewErrorIconColumn : DataGridViewImageColumn
{
    public DataGridViewErrorIconColumn()
    {
        this.CellTemplate = new DataGridViewErrorIconCell();
        this.ValueType = this.CellTemplate.ValueType;
    }
}

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)
    {
        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]

Dim iconColumn As New DataGridViewErrorIconColumn()

iconColumn.DataPropertyName = "Column1"

DataGridView1.Columns.Add(iconColumn)

[C#]

DataGridViewErrorIconColumn iconColumn =

    new DataGridViewErrorIconColumn();

iconColumn.DataPropertyName = "Column1";

DataGridView1.Columns.Add(iconColumn);

 欢迎微信技术交流:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xwLink1996

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值