How to add definition of WithEvents variable which require Handles clause

19,231

Solution 1

The minimal answer is to add WithEvents to aDgv:

Private WithEvents aDgv As DataGridView

Solution 2

The answer of Mark Hurd also works for me. But here's a detailed way on how to do that for beginners like I am.

  • Highlight the variable in your code that has a blue underline
  • Press F12
  • It will take you to the designer.vb
  • You will then immediately see the variable that was highlighted earlier
  • Now just put WithEvents word after the Friend word
  • Done
Share:
19,231
Wine Too
Author by

Wine Too

Updated on June 20, 2022

Comments

  • Wine Too
    Wine Too almost 2 years

    In order to make my program more elegant and better organized in concrete case I would like to change DataGridView1variable with referenced variable on top of my Form1 class

    Private aDgv As DataGridView
    

    And assign value in Form1_Load

    aDgv = DataGridView1
    

    After that I can use aDgv variable across that Form.
    Except in such case:

    Private Sub aDgv_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles aDgv.KeyDown
    aDgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
    'etc...
    End Sub
    

    Where I get an error:

    Handles clause requires a WithEvents variable defined in the containing type or one of its base types. And aDgv variable after Handles clause is blue underlined.

    What to do to get rid of error and get Handles aDgv.SomeEvent to work?
    Of course, with referenced aDgv instead of original control name DataGridView1.