VB .NET – How to use WithEvents Example

As far as I am interesting in probabilities and similar theories in general, today I have decided to illustrate the WithEvents option in Visual Basic with the possibility to bet whether a rolled dice would be big (4,5,6) or small (1,2,3).

So, with the assistance of Visual Studio I have created the following application:

bet3

 

The idea is to guess whether an imaginary dice is small (1,2,3) or big (4,5,6). In case that you guess correctly, your bet is doubled and a small percentage is taken for the bank. Fair. You have two fields where you may give data – the top one where you give your bet money and the bottom  one, where are your current money. In the picture above, the current money is 0 and the bet money is 1000. Which would result in a caught error, if you run.

Pretty much that is all about the simple interface. Let’s go back to the WithEvents part. When we press the “Run the bet”, we roll the imaginary dice and we call a sub called “CheckTheMoney”. This sub looks like this currently:

The idea is that it raises an event, if something of the abovementioned criteria is mentioned. It passes to the event the sender and a string. So, this is what happens later:

And at the end, we have our label named  “lblIssue” updated with the string, which we have passed to the event. You may see the string in the forms here:
bet1 bet2

So pretty much that is all. Just before going to the code, here is a small summary of the names of the objects in the Visual Studio, in case that you would like to build something similar:

  • rbSmaller
  • rbBigger
  • tbInitital
  • tbBet
  • Button1
  • Button2
  • lblStartingMoney
  • lblResult
  • lblCurrentMoney
  • lblIssue

The elements starting with Rb are radiobuttons, tb – textbox, lbl – labels. Button1 and Button2 are buttons.

Pretty much that is all.

Here comes the code, available in GitHub as well:

Enjoy it!

Tagged with: ,