Monday, March 30, 2009

Using WithEvents in Vb.Net


Using withEvents in 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

Private Sub _Charts_Activate() Handles _Charts.Activate
MsgBox(_Charts.Name, MsgBoxStyle.Exclamation, "ActivatedChart")
End Sub
End Class

Now we have to bind every chart in the workbook with the ProxyChart. So I added a WorkbookOpen method in my AddIn, which loops to all the charts in the opened workbook.

Private Sub _App_WorkbookOpen(ByVal Wb As Microsoft.Office.Interop.Excel.Workbook) Handles _App.WorkbookOpen

Dim chrtCol As Object
Dim chtCollection As Collection
Dim chrtObj As ChartObjects

For Each wkSht As Worksheet In Wb.Worksheets
chrtCol = wkSht.ChartObjects(Type.Missing)
chrtObj = TryCast(chrtCol, ChartObjects)

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.

Hope this helps.


No comments: