Listing 1  

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Load

        If Not Page.IsCallback And Not Page.IsPostBack Then
'...The original ESRI code is omitted in this section

            '...Clear the Dropdownlist each time when page is loading
            Me.ActiveLayerList.Items.Clear()

'...Call function to populate all the layer names into an unbound dropdownlist
            PopulateAlltheLayersInDropDownList()

        End If
End Sub
In the event of Page_Load (Default.aspx), two statements are added to clear and refresh layers in Dropdownlist 

Listing 2 

Protected Sub PopulateAlltheLayersInDropDownList()
'...Populate all the selectable feature layers into the DropDownList
'...There is only one selectable layer allowed during spatial select
'...Author: Kuang Yao Lee, Oct 2007

 Try
      '...Create a serverContext using the existing Map Service
	‘...Set the string strGISServer to your GIS Server Host Name
 
   Dim pGISServerConnection As IGISServerConnection = New _
GISServerConnection
   pGISServerConnection.Connect(strGISServer)
   Dim pServerObjectManager As IServerObjectManager = _ 
	pGISServerConnection.ServerObjectManager
   Dim pMapcontext As IServerContext = _ pServerObjectManager.CreateServerContext("AirportService", "MapServer")
   '...Reference to the Map Document and Layers in the Map Service
   Dim ms As ESRI.ArcGIS.Carto.IMapServer = _
 	  	CType(pMapcontext.ServerObject, ESRI.ArcGIS.Carto.IMapServer)
   Dim mso As ESRI.ArcGIS.Carto.IMapServerObjects = _
CType(ms, ESRI.ArcGIS.Carto.IMapServerObjects)
   Dim map As ESRI.ArcGIS.Carto.IMap = mso.Map(ms.DefaultMapName)
   Dim pLayer As ESRI.ArcGIS.Carto.ILayer

   '...Looping through all the layers including the ones in grouplayers
   Dim pEnumLayer As ESRI.ArcGIS.Carto.IEnumLayer
   pEnumLayer = map.Layers(Nothing, True)
   pEnumLayer.Reset()
   pLayer = pEnumLayer.Next

   '...Create an instance object for FeatureLayer
   Dim pFeautreLayer As ESRI.ArcGIS.Carto.IFeatureLayer = _
pMapcontext.CreateObject("esriCarto.FeatureLayer")

   '...Populate all the selectable Feature layers from Map Document   
   Do While Not pLayer Is Nothing
        If TypeOf pLayer Is ESRI.ArcGIS.Carto.IFeatureLayer Then
                pFeautreLayer = pLayer
                If pFeautreLayer.Selectable = True Then
                    Me.ActiveLayerList.Items.Add(pLayer.Name)
                End If
        End If
        pLayer = pEnumLayer.Next
   Loop

   '...Release pointer to avoid locking issues
   pMapcontext.ReleaseContext()
   pMapcontext = Nothing: ms = Nothing: mso = Nothing: map = Nothing
   pLayer = Nothing: pEnumLayer = Nothing: pFeautreLayer = Nothing

   '...the default value is the first layer
   Me.ActiveLayerList.SelectedValue = 0
   
   '...Put the Selected Value in the DropDownList into a session variable  
   Session("ActiveLayer") = Me.ActiveLayerList.SelectedValue

 Catch
   '...Intentionally not to prompt any messages if there is an error
 End Try

End Sub
A subroutine is used to populate all the active layers in Dropdownlist from a Map Service

Protected Sub ActiveLayerList_SelectedIndexChanged(ByVal sender As _   
Object, ByVal e As System.EventArgs) Handles _
ActiveLayerList.SelectedIndexChanged
        
Session("ActiveLayer") = Me.ActiveLayerList.SelectedValue
    
End Sub

A handler for the dropdownlist SelectedIndexChanged event updates the “ActiveLayer” session variable

Listing 3

'...NameSpace – CustomTools.vb
Namespace CustomTools

'...Select Tool Class in repsonse to Spatial Select Event on the Map
Public Class SelectByRectangle
        Implements IMapServerToolAction 

Sub ServerAction(ByVal args As ToolEventArgs) _
Implements IMapServerToolAction.ServerAction

'...Referencing Object - mapctrol to Map Control on Default.aspx 
Dim mapctrl As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map = _
    	CType(args.Control, ESRI.ArcGIS.ADF.Web.UI.WebControls.Map)

'...session variable from Default.aspx stores the name of the activelayer for spatial selection
Dim targetlayername As String = _
CStr(mapctrl.Page.Session("ActiveLayer"))

'...Referecing rectargs to the rectangle drawn on the map control
Dim rectargs As RectangleEventArgs = _
 		CType(args, RectangleEventArgs)
            
Dim myrect As System.Drawing.Rectangle = rectargs.ScreenExtent

'...Record the lower-left corner point
Dim minpnt As ESRI.ArcGIS.ADF.Web.Geometry.Point = _
ESRI.ArcGIS.ADF.Web.Geometry.Point.ToMapPoint(myrect.Left,  myrect.Bottom, mapctrl.Extent, CInt(mapctrl.Width.Value), CInt(mapctrl.Height.Value))

'...Record the upper-right corner point
Dim maxpnt As ESRI.ArcGIS.ADF.Web.Geometry.Point = _
ESRI.ArcGIS.ADF.Web.Geometry.Point.ToMapPoint(myrect.Right, myrect.Top, mapctrl.Extent, CInt(mapctrl.Width.Value), CInt(mapctrl.Height.Value))

'...Convert rectangle into polygon in ADF
Dim mappoly As New ESRI.ArcGIS.ADF.Web.Geometry.Envelope(minpnt, maxpnt)

'...ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer
Dim ags_mf As MapFunctionality = Nothing
Dim gisFunctionality As IGISFunctionality = Nothing

'...Loop through all the functionalites; not Graphic Layer or others
For Each gisFunctionality In mapctrl.GetFunctionalities()
If TypeOf gisFunctionality Is MapFunctionality Then
         ags_mf = CType(gisFunctionality, MapFunctionality)
           Exit For
      End If
Next gisFunctionality

'...Get dataframe from MapService
Dim gisResource As ESRI.ArcGIS.ADF.Web.DataSources.IGISResource = _          	gisFunctionality.Resource

Dim supported As Boolean = gisResource.SupportsFunctionality( _
GetType(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality))

If supported = False Then Exit Sub

'...Get all the queryable layers to String arrays of layerIDs and layerNames
'...Using Namespace - ESRI.ArcGIS.ADF.Web.DataSources
Dim layerIDs As String() = Nothin
Dim layerNames As String() = Nothing
Dim queryFunctionality As IQueryFunctionality = CType(gisResource.CreateFunctionality(GetType(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality), Nothing), ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality)
            queryFunctionality.GetQueryableLayers(Nothing, layerIDs, layerNames)

'...Get Map description 
Dim mapdescription As ESRI.ArcGIS.ADF.ArcGISServer.MapDescription = ags_mf.MapDescription()

‘...Get Layer Description
Dim layerdescs() As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription = mapdescription.LayerDescriptions

‘...Unselect all the selections of all the layers if there is any
Dim i As Integer = 0
Do While i < layerNames.Length
     layerdescs(i).SelectionFeatures = Nothing
     i += 1
Loop
           
'...Define spatial query using the geometry from the map draw event
Dim spatialFilter As ESRI.ArcGIS.ADF.Web.SpatialFilter = _ 
New ESRI.ArcGIS.ADF.Web.SpatialFilter()
spatialFilter.ReturnADFGeometries = True
spatialFilter.MaxRecords = 100
spatialFilter.Geometry = mappoly

Dim activeLayerString As String = targetlayername

i = 0
Dim MyActiveLayerIndex as Long

'...Loop through all the queryable layers in dataframe in MapService
Do While i < layerNames.Length

'...Get the active layer
If layerNames(i).Equals(activeLayerString) Then MyActiveLayerIndex = i
‘...Exit Do if the activelayer is found and show the table
     Exit Do
End If
i += 1
Loop

'...perform spatial query and list selected features in the table
'...Define QueryTables and queryResultsDataTable as result tables
Dim QueryTable2 As New System.Data.DataTable
Dim queryResultsDataTable As New System.Data.DataTable
queryResultsDataTable = queryFunctionality.Query(gisFunctionality.Name, layerIDs(i), spatialFilter)

If queryResultsDataTable.Rows.Count = 0 Then Exit Sub

QueryTable2 = queryResultsDataTable

'...get column of OBJECTID and SHAPE
Dim pObjectIDColum As Integer = 0
Dim dr As Data.DataRow = queryResultsDataTable.Rows(0)
Dim pIndex As Integer = 0

For Each g As System.Data.DataColumn In dr.Table.Columns
    ‘...Get the Colum Index of OBJECTID or FID
   If g.Caption.ToUpper = "OBJECTID" Or g.Caption.ToUpper = "FID" Then
           pObjectIDColum = pIndex
           Exit For
   End If
   pIndex += 1
Next g

'...get the FIDSet from OBJECTID or FID column
Dim j As Long = 0
Dim dr_Rows As Data.DataRow() = queryResultsDataTable.Select(Nothing)                    Dim pFID(dr_Rows.Length - 1) As Integer

‘...Store all the OBJECTID or FID into pFID array
For Each dr_Row As System.Data.DataRow In dr_Rows
       Dim temp_val = (Convert.ToInt32(dr_Row.Item(pObjectIDColum)))
       pFID(j) = temp_val 
       j += 1
Next

'...Build the array of objectids
Dim fids As ESRI.ArcGIS.ADF.ArcGISServer.FIDSet = _
New ESRI.ArcGIS.ADF.ArcGISServer.FIDSet()

Dim ids() As Integer = pFID
fids.FIDArray = ids

'...Define the color for selected features
Dim irgbc As ESRI.ArcGIS.ADF.ArcGISServer.RgbColor = _
New ESRI.ArcGIS.ADF.ArcGISServer.RgbColor()
irgbc.Red = 0
irgbc.Green = 255
irgbc.Blue = 255

Dim pColor As ESRI.ArcGIS.ADF.ArcGISServer.Color
pColor = irgbc

'...Define selected features and the color in layerdescription object
Dim layerDesc As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription = _
                layerdescs(layerIDs(MyActiveLayerIndex))
layerDesc.SelectionColor = pColor
layerDesc.SelectionFeatures = fids.FIDArray
layerDesc.ShowSelectionBuffer = False

'...Refresh Map to show selected features in highlighted color
mapctrl.Refresh()

'...Create a GridView Object
Dim gdview As New GridView

'...Get reference to Floating Panel in Defaut.aspx
Dim gvviewPanel As FloatingPanel = _ 	CType(mapctrl.Page.FindControl("GridViewFloatingPanel"), FloatingPanel)

'...Check = True, then show selected features
   Dim cbx As CheckBox = _ 
CType(mapctrl.Page.FindControl("ViewTableCheckBox1"), CheckBox)
   Dim cbxChecked As Boolean = cbx.Checked   
If cbxChanged = True Then  
   gvviewPanel.Visible = True
   QueryTable2.TableName = "SelectTable"
   gdview.DataSource = QueryTable2
   gdview.DataBind()
   gvviewPanel.Controls.Add(gdview)
   gvviewPanel.Refresh()
End If

'...Enforce Garbage Collector
mapctrl = Nothing
rectargs = Nothing
minpnt = Nothing
maxpnt = Nothing
mappoly = Nothing
ags_mf = Nothing
gisFunctionality = Nothing
queryResultsDataTable = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub 'IMapServerToolAction.ServerAction

End Class 'End of SelectTool
The VB code for SelectByRectangle were modified from a ESRI sample –ArcGIS_SelectBufferToolVBNet.zip

Listing 4 

Public Class SelectToolByShape
    Implements IMapServerToolAction 

Sub ServerAction(ByVal args As ToolEventArgs) _
Implements IMapServerToolAction.ServerAction

    Dim targetlayername As String = CStr(mapctrl.Page.Session("ActiveLayer"))

    ‘...### This section differs from SelectTool – Select By Retangle 
    ‘...Define a polygon Event Argument from the screendrawing on the Map Control
    Dim polyargs As PolygonEventArgs = args
    Dim screenpoly As System.Drawing.Point() = polyargs.Vectors

    ‘...Capture point vectors from screen polygon collection
    Dim pc As ESRI.ArcGIS.ADF.Web.Geometry.PointCollection = _
        New ESRI.ArcGIS.ADF.Web.Geometry.PointCollection()
    For Each dpnt As System.Drawing.Point In screenpoly
             pc.Add(ESRI.ArcGIS.ADF.Web.Geometry.Point.ToMapPoint(dpnt, _
             mapctrl.Extent, CInt(mapctrl.Width.Value), _
             CInt(mapctrl.Height.Value)))

    Next

    ‘...Define Geometry Ring by collecting all the points 
    Dim ring As ESRI.ArcGIS.ADF.Web.Geometry.Ring = _
        New ESRI.ArcGIS.ADF.Web.Geometry.Ring()
    ring.Points = pc
    
    ‘...Define multiple Geometry Rings by collecting single ring
    Dim rings As ESRI.ArcGIS.ADF.Web.Geometry.RingCollection = _
        New ESRI.ArcGIS.ADF.Web.Geometry.RingCollection()
    rings.Add(ring)

   ‘...Compose polygon from multiple ring collection
    Dim mappoly As ESRI.ArcGIS.ADF.Web.Geometry.Polygon = _
         New ESRI.ArcGIS.ADF.Web.Geometry.Polygon()
    mappoly.Rings = rings

    ‘...### Rest of implemention …