Background
When I hit a button on a WinForm, I am loading data into a BindingSource that serves as the data source for a DataGridView. Once the data is loaded, I go through and make some modifications to the DataGridView; in particular, I 1) set any cells that are valued as DBNull to the string value “NULL”, 2) italicize the same cells, and 3) highlight some rows.
Simple example of what I’m doing:
private void btnFetch_Click(object sender, EventArgs e)
{
// If there's already a DataSource, Dispose of it.
if (bsMessageTracking.DataSource != null)
{
(bsMessageTracking.DataSource as DataTable).Dispose();
}
// Get new DataSource.
bsMessageTracking.DataSource = GetDataTable(); // Details not relevant.
// Show NULL values.
foreach (DataGridViewRow row in dgv.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value is DBNull)
{
cell.Value = "NULL";
cell.Style.Font = new Font(dgv.DefaultCellStyle.Font, FontStyle.Italic);
}
}
}
// Apply highlighting.
foreach (DataGridViewRow row in dgvMessageTracking.Rows)
{
if (HighlightRow(row)) // Details not relevant.
{
row.DefaultCellStyle.BackColor = Color.LightYellow;
}
}
}
The data gets loaded based on input into a TextBox on the form.
Situation
Everything works great if this occurs on the button click. However, in order to provide some convenience to the user, I am allowing this form to get loaded with data prepopulated – the main form will instantiate this form with the data to put into the TextBox, and this btnFetch_Click handler will get called from the constructor:
internal MessageTracking(string ID)
{
InitializeComponent();
// Setup data source.
dgvMessageTracking.DataSource = bsMessageTracking;
// Set ID and run query.
if (ID != null)
{
// Set ID.
txtlID.Text = ID;
// Run!
btnFetch_Click(null, null);
}
}
The value of the cells gets changed (so I see NULL), but the font and the highlighting don’t stick.
What I’ve tried
If I replicate the highlighting code in the OnShown method, the highlighting sticks. However, replicating the font code there doesn’t work. I can make the font stick if I put it in CellFormatting, but that seems like overkill to me, because I only need this to be run once when the form is loaded – it works fine if the process is run after the form is visible.
Plea
If anyone has any suggestions, I would appreciate them. Thanks!
I guess, from the lack of responses, that there is no better way if you want the formatting shown when the form first becomes visible. I have removed the
Show NULL valuesportion of thebtnFetch_Clickhandler and added thisdgvMessageTracking_CellFormattinghandler to handle this functionality at all times: