■■■

2016年4月2日土曜日

DataGridViewでセルに強制的に画像を表示する方法

DataGridViewでセルに強制的に画像を表示する方法
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
Dim iconColumn As New DataGridViewErrorIconColumn()
iconColumn.DataPropertyName = "col1"
dgv1.Columns.Add(iconColumn)
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;
}
}
}
DataGridViewErrorIconColumn iconColumn =
new DataGridViewErrorIconColumn();
iconColumn.DataPropertyName = "col1";
dgv1.Columns.Add(iconColumn);
■■■