Monday, March 30, 2009

Using WithEvents in Vb.Net

Hi,

Using withEvents in VB.net is very easy. I faced lot of problem while accessing the events. For example, activating a chart does not fire a selection change event. I had to do something like whenever I select my chart, my custom menu should appear. I couldn't find doing it in C#(please send a mail if you find it), but in VB.Net it is very easy.

So to take a small example, I have taken a scenario, if I select any of the chart in my workbook, it should display a message. So first of all I created a Class ProxyCharts. The purpose of the class is to serve a Wrapper for Charts Object. This is the class where we will bind our chart objects to WithEvent keyword. So as a wrapper, we will have as many Wrappers as the number of charts available in the workbook. The proxy chart is as follows:

Public Class ProxyCharts Private WithEvents _Charts As Chart

Public WriteOnly Property _Chart() As Chart Set(ByVal value As Chart) _Charts = value End Set End Property

If Not chrtObj Is Nothing Then For Each chrt As ChartObject In chrtObj Dim chh As New ProxyCharts() chh._Chart = chrt.Chart Next chrt End If Next wkSht End Sub

As soon as a workbook is opened, the WorkbookOpen method is called by default and binds all the charts in the opened workbook with ProxyChartType. After binding, the above code will display a message as soon as you select any of the pre existing charts in workbook.