Preface
To make the data display more eye-catching in the data display control, a style is usually added for the data display control. This topic describes how to display the zebra line style of the datagridview Data Control.
Content
Method 1:
Implement it by yourself.
After the data control is bound, the rowprepaint event of the datagridview is used. This event is triggered when row painting is executed before any cell painting occurs.
Private Void Datagridview_rowprepaint ( Object Sender, datagridviewrowprepainteventargs E)
{
If (Sender Is Datagridview)
{
Datagridview dgv = (Datagridview) sender;
If (E. rowindex + 1 ) % 2 = 0 ) // If this behavior is a multiple of 2, the color is used.
{
Dgv. Rows [E. rowindex]. defaultcellstyle. backcolor = Color. lightblue;
}
}
}
Use the precedingCodeYou can see that the datagridview style is a zebra crossing. However, we need to pay attention to the details. When we click the row in the header, it is usually sorted by the column currently clicked, which disrupts the zebra line we have drawn. So what should we do when we click the row in the header!
Two events are used when you click the header cell. One is cellclick, and the other is cellmouseclick. Let's briefly describe the differences between the two.
Here is a reference:
"The cellclick event does not receive information about the mouse position. If the event handler needs information about the mouse position, use the cellmouseclick event ".
This is the content of the cellmouseclick datagridviewcellmouseeventargs.
This is the content of the cellclick datagridviewcelleventargs.
The cellmouseclick event contains information about the mouse position.
The cellmouseclick event is used here, And the cellclick event can also be used completely.
Private Void Datagridview_cellmouseclick ( Object Sender, datagridviewcellmouseeventargs E)
{
If (Sender Is Datagridview)
{
Datagridview dgv = (Datagridview) sender;
If (E. rowindex = - 1 ) // If this behavior Header
{
Foreach (Datagridviewrow row In Dgv. Rows) /* Set the background color of all rows to white */
{
Row. defaultcellstyle. backcolor = Color. White;
}
}
}
}
Okay. You can also click the header.
Method 2:
One blow is mandatory.
In fact, the zebra effect has been implemented in the datagridview control, that is, the alternatingrowdefaultcellstyle attribute. You only need to modify the backcolor of its attribute to achieve this effect.
In addition, thisProgramTest in. Net framework3.5.