DataGridView CellFormatting event preventing form painting
I am using C#, Winforms, and .Net 3.5
My form has a custom DataGridView
(double-buffered to prevent flickering during my cellformatting events, as seen here). When I perform a database search, I bind the resulting dataset to the datagridview
.
I handle the CellFormatting
event to paint rows a certain color, depending on their data.
My DataGridView code:
resultsGridView.DataSource = results.DefaultViewManager.DataSet.Tables[0];
resultsGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue;
resultsGridView.BorderStyle = BorderStyle.Fixed3D;
resultsGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(resultsGridView_CellFormatting);
My CellFormatting code:
void resultsGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int rowIndex = e.RowIndex;
DataGridViewRow therow = resultsGridView.Rows[rowIndex];
if ((bool)therow.Cells["Sealed"].Value == true)
{
therow.DefaultCellStyle.BackColor = Color.Pink;
}
if (therow.Cells["Database"].Value as string == "PNG")
{
therow.DefaultCellStyle.BackColor = Color.LightGreen;
}
}
Everything works great except that, when I handle the CellFormatting, the whole form's Paint event seems to be turned off. The cursor stops blinking in the textbox, and the form's menustrip looks like this:
The top is before a search, the bottom after. The menubar won't redraw until I mouse over where the menuitems are, and then the last item to be highlighted will stay that way when I move the mouse out of the menubar. Mo开发者_Go百科ving the form seems to cause it to repaint, but then the problem remains.
Commenting out the resultsGridView.CellFormatting
line in the datagridview code completely fixes the problem.
Am I painting the cells wrong, or is there something else I need to handle?
You are probably causing an exception inside this event. I'm not sure how the handling is defined, but surrounding the code with a try catch would be a first step.
try
{
int rowIndex = e.RowIndex;
....
}
catch(Exception ex)
{
System.Diagnostics.Trace.Error(ex.message);
}
On a second look, I don't think therow.Cells["Sealed"]
will work. Try something like therow.Cells["dataGridViewTextBoxColumn2"]
. Cells is indexed by Column Name, not DataPropertyName.
精彩评论