Question

I just created a test project to debug an issue i ran into, and can't seem to understand what's going on in here... In this test project, i have just a Form, a TabControl, and a DataGridView (called dgvTest) in a "background" page within the tabControl (page 2 or later). Here's the code i've used to reproduce the problem:

    private void Form1_Load(object sender, EventArgs e)
    {
        dgvTest.DataSource = GetDataSource();
        DataGridViewColumn customColumn = new DataGridViewColumn(new DataGridViewTextBoxCell());
        customColumn.DataPropertyName = "SampleColumn";
        dgvTest.Columns.Insert(dgvTest.Columns["SampleColumn"].Index, customColumn);
        //#region Attempt #1
        //dgvTest.Columns.Remove("SampleColumn");
        //customColumn.Name = "SampleColumn";
        //#endregion
        #region Attempt #2
        dgvTest.Columns["SampleColumn"].Visible = false;
        customColumn.Name = "SampleColumnCbo";
        #endregion
        dgvTest.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
    }

    private DataTable GetDataSource()
    {
        DataTable result = new DataTable();
        result.Columns.Add("SampleColumn");
        result.Columns.Add("Q");
        //no rows needed
        return result;
    }

Now, if i run this, the DataGridView will only get fully initialized (i mean, calling its AutoGenerateDataBoundColumns) after i try to select the tabPage it's at... At which point it will throw an InvalidOperationException that says either "Column cannot be added because its CellType property is null." or "At least one of the DataGridView control's columns has no cell template." (basically, the same thing; but i've only gotten the first message in my initial project and in the early stages of the test project, before i've minimized the code to the current state). The strange thing is that this Exception isn't thrown if dgvTest is placed on the 1st tagPage or directly within the Form itself.

Any ideas? Thanks in advance.

Was it helpful?

Solution

It seems this is related to the fact that your DataGridView is not visible (on the background tab) when you set its DataSource (when Form1_Load code is called) even though the exception is not triggered until later. For instance it will work if you handle the VisibleChanged event of the DataGridView and move your Form1_Load code to there instead only taking care to ensure that the initialization code only fires on the first time TabPage n is clicked (effectively a pseudo-Initialized event).

private bool dgvInitialized = false;

private void dgvTest_VisibleChanged(object sender, EventArgs e)
{
    if (dgvTest.Visible && !dgvInitialized)
    {
        dgvInitialized = true;

        // Move Form1_Load code to here instead...
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top