I want to implement a column with a progress bar, for example.
ImplementationCode:
1. Add reference
Using System. drawing;
Using System. componentmodel;
2. Custom datagridviewcolumn
/// <Summary>
/// The progress column. Cell content format: Value/total value Eric
/// </Summary>
[Description ( " The progress column. Cell content format: Value/Total Value " )]
Public Class Datagridviewprocesscolumn: datagridviewcolumn
{
Public Datagridviewprocesscolumn ()
: Base ( New Datagridviewprocesscell ())
{
}
}
3. Custom datagridviewcell
/// <Summary>
/// Cell with progress. Cell content format: Value/total value Eric
/// </Summary>
[Description ( " Cell with progress. Cell content format: Value/Total Value " )]
Public Class Datagridviewprocesscell: datagridviewcell
{
/// <Summary>
/// Progress bar View
/// </Summary>
Protected Color _ processcolor = Color. fromargb ( 64 , 192 , 192 );
PublicDatagridviewprocesscell ()
{
}
PublicDatagridviewprocesscell (color processbackcolor)
:Base()
{
_ Processcolor=Processbackcolor;
}
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)
{
Using (Solidbrush backbrush = New Solidbrush (cellstyle. backcolor ))
{
// Dimension cell background
Graphics. fillrectangle (backbrush, cellbounds );
}
Base . Paintborder (graphics, clipbounds, cellbounds, cellstyle, advancedborderstyle );
Float Percent = 0f;
If (Value ! = Null )
{
String [] Resultandtotal = Value. tostring (). Split ( ' / ' );
If (Resultandtotal. Count () = 2 )
{
Float Result = 0 ;
Float Total = 0 ;
If ( ! Float . Tryparse (resultandtotal [ 0 ], Out Result ))
{
Percent = 0 ;
}
Else If ( ! Float . Tryparse (resultandtotal [ 1 ], Out Total ))
{
Percent = 0 ;
}
Else
{
Percent = Result / Total;
}
}
}
Using (Solidbrush forebrush = New Solidbrush (_ processcolor ))
{
// Draw Progress Chart
Graphics. fillrectangle (forebrush, cellbounds. X, cellbounds. Y + Cellbounds. Height / 4 , Cellbounds. Width * Percent, cellbounds. Height / 2 );
}
Using (Solidbrush residuebrush = New Solidbrush (color. lightgray ))
{
// Remaining part of the progress bar
Graphics. fillrectangle (residuebrush, cellbounds. x + Cellbounds. Width * Percent, cellbounds. Y + Cellbounds. Height / 4 , Cellbounds. Width * ( 1 - Percent), cellbounds. Height / 2 );
}
String Celltext = Value. tostring ();
Sizef SF = Graphics. measurestring (celltext, cellstyle. font );
Float X = Cellbounds. x + (Cellbounds. Width - SF. width) / 2f;
Float Y = Cellbounds. Y + (Cellbounds. Height - SF. Height) / 2f;
// Dimension cell text
Graphics. drawstring (celltext, cellstyle. Font, New Solidbrush (cellstyle. forecolor), x, y );
}
}
Run: if the value of a cell is 1/20. The result is the same as the last result in the figure.