Search code examples
vb.netdatagridviewdatagridviewcolumn

Setting DataGridView.RowCount to NumericUpDown.Value adds extra column


So I have a form on which I have a NumericUpDown control (I'll call it my num picker), and a DataGridView (I'll call it my grid). My grid is currently unbound and I manually added columns to it in design, and when I run my form it's all fine. So in the code I added this method:

Private Sub numPicker_ValueChanged(sender As Object, e As EventArgs) Handles numPicker.ValueChanged
    DataGridView.RowCount = CInt(numPicker.Value)
End Sub

With that, at runtime my grid has an extra un-titled column in the front. If I comment out the assignment there is no extra column...if I uncomment it there is an extra column.

I have another form with a similar setup and for whatever reason that form acts fine...there is no extra column being added. So I just have no idea why one form would add a column to my grid and another wouldn't...nor do I have any idea how to deal with it.

Any ideas?

NOTE for clarification: MSDN's article on the RowCount property (http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowcount%28v=vs.110%29.aspx) states "If you set the RowCount property to a value greater than 0 for a DataGridView control without columns, a DataGridViewTextBoxColumn is added automatically." But I do already have columns. And in the form Load I set the row count to 1 (the num picker's value is also 1). When that assignment line is commented out, my form loads with 1 row in the grid and no extra column.


Solution

  • The ValueChanged() event is firing and then changing the number of rows before the DataGridView has been completely initialized.

    Add a check in there and the extra column should go away:

    Private Sub numPicker_ValueChanged(sender As Object, e As EventArgs) Handles numPicker.ValueChanged
        If DataGridView.IsHandleCreated Then
            DataGridView.RowCount = CInt(numPicker.Value)
        End If
    End Sub