Select to view content in your preferred language

null value for the defined graphicsLayer in Drive time

619
2
10-21-2010 08:41 AM
ShaningYu
Honored Contributor
I used ESRI's source code: Drive Time from http://help.arcgis.com/en/webapi/silverlight/samples/start.htm#DriveTimes, and then have some customizations.
In the xaml file, the GraphicsLayer is defined and named as 'MyGraphicsLayer':
        <esri:Map x:Name="_Map" Background="White" Extent="-122.5009,37.741,-122.3721,37.8089
            <esri:GraphicsLayer ID="MyGraphicsLayer">
In the .cs file,
        private void _Map_MouseClick(object sender, ESRI.ArcGIS.Client.Map.MouseEventArgs e)
        {
            _geoprocessorTask.CancelAsync();

            GraphicsLayer graphicsLayer = _Map.Layers["MyGraphicsLayer"] as GraphicsLayer;
            Graphic graphic = new Graphic()
            {
                Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as Symbol,
                Geometry = e.MapPoint,
            };
            graphic.Attributes.Add("Info", "Start location");
            string latlon = String.Format("{0}, {1}", e.MapPoint.X, e.MapPoint.Y);
            graphic.Attributes.Add("LatLon", latlon);
            graphic.SetZIndex(1);
            graphicsLayer.Graphics.Add(graphic);
            ....
I received an exception for graphicsLayer that is null.  In this piece of code, the graphicsLayer has been defined as 'MyGraphicsLayer' and should not be null per my understanding.  If you can find the bug and post your fidning, I will greatly appreciate.
Have a nice day!
0 Kudos
2 Replies
JenniferNery
Esri Regular Contributor
I do not see anything wrong in the code you shared. It looks exactly like the sample, except Map was renamed.

Check everywhere for GraphicsLayer, maybe it fails to retrieve the layer somewhere else not in this line.  Check the call stack, this usually tells you which code was executed before the NullReference exception.
0 Kudos
ShaningYu
Honored Contributor
Jennifer:
Thanks for your response.  I have realized that the bug is due to that I set the map object defined in this user control (_Map) as the parent one:
  _Map = _Parent.MyMap;
Then, the layer defined in the user control becomes un-recognized:
  GraphicsLayer graphicsLayer = _Map.Layers["MyGraphicsLayer"] as GraphicsLayer;
I re-coded and then the problem got solved.  Thanks and have a nice day!
Yours,
Shaning
0 Kudos