In. Net winform, The datagridview isProgramDevelopment provides a lot of convenience, so we don't need to do a lot of extra work to get some basic functions, such as Clicking column title sorting, row selection, changing column width and row width, and the automatic tooltip function of cell content. However, datagridview facilitates development and creates some minor problems. For example, for the automatic tooltip function of cells, how can we customize the style of the tooltip prompt box? Here is a sectionCodeIt can help us complete this function.
First, you need to add a tooltip control on the form, and then refer to the following code to add the cellmousemove and mouseleave events to your datagridview, you also need to add a draw event to the tooltip control to define the specific rendering of the tooltip.
Public Partial Class Mainform: Form
{
Private Int Cellcolumnindex = - 1 , Cellrowindex = - 1 ;
PublicMainform ()
{
Initializecomponent ();
This . Testdatagri. showcelltooltips = False ;
This . Tooltip. automaticdelay = 0 ;
This . Tooltip. ownerdraw = True ;
This . Tooltip. showalways = True ;
This . Tooltip. tooltiptitle = " Custom tooltip: " ;
This . Tooltip. useanimation = False ;
This . Tooltip. usefading = False ;
}
Private Void Testdatagridview_cellmousemove ( Object Sender, datagridviewcellmouseeventargs E)
{
If (E. rowindex < 0 | E. columnindex < 0 )
{
Return ;
}
This. Tooltip. Hide (This. Testdatagridview );
This. Cellcolumnindex=E. columnindex;
This. Cellrowindex=E. rowindex;
If ( This . Cellcolumnindex > = 0 && This . Cellrowindex > = 0 )
{
Point mousepos = Pointtoclient (mouseposition );
String Tip = " Tip is " + This . Testdatagridview [ This . Cellcolumnindex, This . Cellrowindex]. value. tostring ();
This . Tooltip. Show (tip, This . Testdatagridview, mousepos );
}
}
Private VoidTestdatagridview_mouseleave (ObjectSender, eventargs E)
{
This. Tooltip. Hide (This. Testdatagridview );
}
Private Void Tooltip_draw ( Object Sender, drawtooltipeventargs E)
{
E. Graphics. fillrectangle (brushes. aliceblue, E. bounds );
E. Graphics. drawrectangle (pens. Chocolate, New Rectangle ( 0 , 0 , E. bounds. Width - 1 , E. bounds. Height - 1 ));
E. Graphics. drawstring ( This . Tooltip. tooltiptitle + E. tooltiptext, E. Font, brushes. Red, E. bounds );
}
}
Testdview dview is the ID of the dview, and tooltip is the ID of the tooltip.