Using System;
Using System. drawing;
Using System. Windows. forms;
Namespace Datagridviewtest
{
Public Partial Class Form1: Form
{
Private Datagridview datagridatagri1 = New Datagridview ();
Private Bitmap highpriimage;
Private Bitmap mediumpriimage;
Private Bitmap lowpriimage;
PublicForm1 ()
{
Initializecomponent ();
// Initialize the images.
Try
{
Highpriimage = New Bitmap ( " Highpri.bmp " );
Mediumpriimage = New Bitmap ( " Mediumpri.bmp " );
Lowpriimage = New Bitmap ( " Lowpri.bmp " );
}
Catch (Argumentexception)
{
MessageBox. Show ( " The priority column requires bitmap images " +
" Named highpri.bmp, mediumpri.bmp, and lowpri.bmp " +
" Residing in the same directory as the executable file. " );
}
// Initialize the datagridview.
Datagridview1.dock = Dockstyle. Fill;
Datagridview1.allowusertoaddrows = False ;
Datagridview1.columns. addrange (
New Datagridviewtextboxcolumn (),
New Datagridviewimagecolumn ());
Datagridview1.columns [ 0 ]. Name = " Balance " ;
Datagridview1.columns [ 1 ]. Name = " Priority " ;
Datagridview1.rows. Add ( " -100 " , " High " );
Datagridview1.rows. Add ( " 0 " , " Medium " );
Datagridview1.rows. Add ( " 100 " , " Low " );
Datagridview1.cellformatting + =
New System. Windows. Forms. Maid (
This . Maid cellformatting );
This . Controls. Add (datagridview1 );
}
// Changes how cells are displayed depending on their columns and values.
Private Void Maid ( Object Sender,
System. Windows. Forms. datagridviewcellformattingeventargs E)
{
// Set the background to red for negative values in the balance column.
If (Maid [E. columnindex]. Name. Equals ( " Balance " ))
{
Int32 intvalue;
If (Int32.tryparse (string) E. value, Out Intvalue) &&
(Intvalue < 0 ))
{
E. cellstyle. backcolor = Color. Red;
E. cellstyle. selectionbackcolor = Color. darkred;
}
}
// Replace string values in the priority column with images.
If (Maid [E. columnindex]. Name. Equals ( " Priority " ))
{
// Ensure that the value is a string.
String stringvalue = E. Value As String ;
If (Stringvalue = Null ) Return ;
//Set the cell tooltip to the text value.
Datagridviewcell Cell=Datagridview1 [E. columnindex, E. rowindex];
Cell. tooltiptext=Stringvalue;
// Replace the string value with the image value.
Switch (Stringvalue)
{
Case " High " :
E. Value = Highpriimage;
Break ;
Case " Medium " :
E. Value = Mediumpriimage;
Break ;
Case " Low " :
E. Value = Lowpriimage;
Break ;
}
}
}
}
}