To change the DataGridViewComboBoxCell color(style) dynamically
I have a DataGridview with several columns, and one of the column is DataGridViewComboBoxColumn.
The scenario is, When the user selects some value from the combobox (selected index > 0), the whole row of the selected cell will be shown in white. If the user selects the empty value for the combobox (selected index is 0) then the whole row will be shown in Yellow, and this combobox cell should be shown in Red.
I could able to achieve showing the whole row in yellow except for the combobox column.
private void grdCurve_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
//for datatype column
if (grdCurve.CurrentCell.ColumnIndex == DATATYPE_COLUMN_INDEX)
{
// Check box column
ComboBox comboBox = e.Control as ComboBox;
comboBox.SelectedIndexChanged -= new EventHandler(comboBox_SelectedIndexChanged);
comboBox.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
}
}
void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (selectedIndex >= 0)
{
if (!ValidateMnemonic(mnRow, row))
{
MarkInvalidRow(row);
}
else
{
MarkValidRow(row);
}
}
}
private void MarkInvalidRow(DataGridViewRow row)
{
DataGridViewCellStyle style = new DataGridViewCellStyle();
if (m_InvalidRowTable.Count > 0)
{
if (m_InvalidRowTable.ContainsKey(row.Index))
{
int col = Convert.ToInt32(m_InvalidRowTable[row.Index]);
DataGridViewCell cell = row.Cells[col];
MarkInvalidRowColor(row);
style.BackColor = Color.Red;
style.SelectionBackColor = Color.Red;
cell.Style = style;
if (grdCurve.CurrentCell is DataGridViewComboBoxCell)
{
grdCurve.CurrentCell.Style = style;
}
}
else
{
MarkInvalidRowColor(row);
}
}
else
{
MarkInvalidRowColor(row);
}
m_InvalidRowTable.Remove(row.Index);
}
private void grdCurve_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//do nothing
}
private void grdCurve_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (grdCurve.CurrentCell is DataGridViewCheckBoxCell)
grdCurve.CommitEdit(DataGridViewDataErrorContexts.Commit);
if (grdCurve.CurrentCell is DataGridViewComboBoxCell && grdCurve.IsC开发者_开发问答urrentCellDirty)
grdCurve.CommitEdit(DataGridViewDataErrorContexts.Commit);
grdCurve.EndEdit();
}
When i change the item in the combobox to empty, I expect the combobox to be marked in red color. But, it shows in white and when i click on some other cell, the red color gets updated in the combobox cell.
Please help.
Thanks, Prasad
Take a look here http://msdn.microsoft.com/en-us/library/1yef90x0.aspx theres is a section entitled setting cell styles dynamically. You should implement a handler for DataGridView.CellFormatting
精彩评论