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 this is happening? How can I make it color the cells right from the beginning?

Thanks!

Why this is happening? How can I make it color the cells right from the beginning?

You don't want to. Classes inheriting from controls (including forms) rarely need code in the constructor aside from designer generated code. You should place this code in the form's Load event. A lot of controls will not work properly, as is the case here, if you attempt to initialize them before the parent form's window handle has been created (load event).

The load event will run before the form is ever painted on the screen so it will be "right from the beginning" with respect to what the end-user sees.

Hi, thanks.

I tried to make a load event in the form1.designer.cs (and added the related code in form1.cs):

this.Load += new System.EventHandler(this.Form1_Load);

But it didn't work (in terms of coloring the datagrid), so I've changed it to:

this.Activated += new System.EventHandler(this.Form1_Activate);

And it did work! But why didn't it worked on load event?

Thanks,

to create events, put the code in form constructor.

//on form1:
public Fomr1()
{
     InitializeComponent();
     this.Load += new System.EventHandler(Form1_Load);
}

private void Form1_Load(object sender, EventArgs e)
{
     //this will now fire at loading time!
}

Double clicking a Form in the Designer window will create a Load event and put you right in the source , ready to edit.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.