Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add definition of WithEvents variable which require Handles clause

Tags:

vb.net

events

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.

like image 333
Wine Too Avatar asked Dec 21 '12 16:12

Wine Too


2 Answers

The minimal answer is to add WithEvents to aDgv:

Private WithEvents aDgv As DataGridView
like image 84
Mark Hurd Avatar answered Sep 29 '22 09:09

Mark Hurd


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
like image 40
montesajudy Avatar answered Sep 29 '22 08:09

montesajudy