1

I have written a class to show a form that contains a datagridview. The class connects to a database, creates a datatable and uses that as the source for the datagridview.

I then add the datagridview to the form using Controls.Add().

When the form is displayed using ShowDialog(), the columns are there as expected.

However, if I try to edit the datagridview columns (width, etc) prior to ShowDialog(), I get an error. If I count the rows in debugging, they are 0. However, if I step into the ShowDialog() action (bypassing anything that tries to edit the columns), the form appears with all the columns.

I'm wondering where I need to edit the datagridview columns before they appear to the user.

Any help on this would be much appreciated.

Chris
  • 8,527
  • 10
  • 34
  • 51
Sparked
  • 844
  • 10
  • 25
  • What Exception do you get? May help to see some of the code. You may be setting properties before the grid is created? – Ric Sep 11 '13 at 14:40
  • @Ric Yes, I'm definitely trying to set something before it is created. The code goes like this: _Dim frm As New Form; dim dgv as New DataGridView; dgv.Width = 200, dgv.Datasource = [datatable]; frm.ShowDialog()_ If I run that the dgv appears with the data from the datatable. However, if I try to refer to a column (_dgv.Column(0).width = 25_) **before** ShowDialog() I get an error, as the column count is zero. I'd like to be able to adjust column widths, etc, before ShowDialog. – Sparked Sep 11 '13 at 15:10
  • Thanks @Ric. I've answered my own question below. – Sparked Sep 11 '13 at 15:16

2 Answers2

0

Got it. I needed to add a Handler to the Form Load event and put the adjustments in there.

Sparked
  • 844
  • 10
  • 25
0

However, if I try to edit the datagridview columns (width, etc) prior to ShowDialog, I get an error. (...) Got it. I needed to add a Handler to the Form Load event and put the adjustments in there.

I guess you try to access columns that do not exist yet.

You are using the DataGridView.AutoGenerateColumns functionnality and even if you set the DataSource property, The DatagridView won't create columns until the grid is displayed.

It's why it doesn't work in when you try to access columns before you call ShowDialog(), and it works in form_Load event or after that the grid has been displayed.

This is a common issue:

Using form_Load is maybe a possible workaround (which is not guaranteed to work every time with), but I recommend you to use instead the DataGridView.DataBindingComplete event which is especially designed to handle this situation.

Community
  • 1
  • 1
Chris
  • 8,527
  • 10
  • 34
  • 51