vb.netwinformsdatagridviewform-load

Setting the value of cell in datagridview not working in form load


This is my code for setting the value in datagridview cell:

For i = 0 To dvJOBranch.Rows.Count - 1
        dvJOBranch.Rows(i).Cells.Item("XS").Value = 0
        dvJOBranch.Rows(i).Cells.Item("S").Value = 0
        dvJOBranch.Rows(i).Cells.Item("M").Value = 0
        dvJOBranch.Rows(i).Cells.Item("L").Value = 0
        dvJOBranch.Rows(i).Cells.Item("XL").Value = 0
Next

Its working in button event, shown form event, but not in form load, and there are no errors.

My question is why it does not work in form load?


Solution

  • My guess is that 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 could explain why it's not working in formload (grid is not initialized yet) and it works after (with shown event for example).

    So it's possible that:

    Using form_shown is maybe a possible workaround, but I recommend you to use the DataGridView.DataBindingComplete event which is more especially designed to handle this situation.

    See also these related issues (same cause):