Problem formatting DataGridView on load
I'm trying to format a DataGridView, with style color, etc. The DGV loads (via buildGrid method) at the startup of the form, as you can see in the constructor's code:
public Report1(DataSet dsReport1, string sDateRep)
{
开发者_开发知识库InitializeComponent();
sDate = sDateRep;
dsReportGrid = dsReport1;
orgDataset();
buildGrid();
}
Here's the code for the DGV:
private void buildGrid()
{
try
{
dataGridView1.DataSource = dsReportGrid.Tables[0];
Controls.Add(dataGridView1);
dataGridView1.Visible = true;
dataGridView1.Rows[2].Cells[1].Style.ForeColor = Color.Red;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It loads the DGV fine, problem is that it won't color the cells like I wish it would, it's just leaves it black.
Funny thing, when I call buildGrid through any other method, outside of the constructor, it does color it! for example:
private void Form1_Resize(object sender, EventArgs e)
{
buildGrid();
}
Why is it happening? How can I make it color the cells right from the beginning?
Thanks!
The problem is that the databinding has not yet completed inside your constructur so any changes to the grid are removed (I'm not actually 100% sure why they are removed, since the rows and cells are there, but this is how it works).
The correct place to put this sort of formatting is within the DataBindingComplete
event handler - that event is raised after databinding has finished but before the grid is drawn.
public Report1(DataSet dsReport1, string sDateRep)
{
InitializeComponent();
sDate = sDateRep;
dsReportGrid = dsReport1;
orgDataset();
dataGridView1.DataSource = dsReportGrid.Tables[0];
Controls.Add(dataGridView1);
dataGridView1.Visible = true;
dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete;
}
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
dataGridView1.Rows[2].Cells[1].Style.ForeColor = Color.Red;
}
精彩评论