Pergunta

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?

Foi útil?

Solução

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:

  • you try to access items that do not exist yet (but the code should raise an exception)
  • or you access valid rows or columns, but they are replaced when the grid is displayed the first time or bound again to a data source, and so your code has no effect (probably your case since you do not mention an exception).

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):

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top