Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to to pass a rectangle from one function to a second function
For some reason the rectangel read to the event function as null
How can I do this?


C#
private Point startpoint;
        private Rectangle rect;
 
        private void canvas1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            
            startpoint = Mouse.GetPosition(canvas1);
 
  // the rectengle that i creat and i what to pass him to the canvas1_MouseMove Event function 
            Rectangle rect = new Rectangle();
            rect.Stroke = Brushes.Black;
            rect.StrokeThickness = 1;
 

            canvas1.Children.Add(rect);
       
 

        }
 
        
 
        private void canvas1_MouseMove(object sender, MouseEventArgs e)
        {
           //to here i want to pass the rectangle  
           // when i debug the code the rect value is null!
           // so i cant control his Properties
 
 
                rect.Width = 5;// her i got excsption 
                               //"Object reference not set to an instance of an object."
                rect.Height = 6;
 
      
 
           
           
        }
Posted
Comments
BillWoodruff 14-Nov-13 11:45am    
Repost of: http://www.codeproject.com/Questions/682669/how-to-pass-rectenge-from-one-event-function-to-an

1 solution

A couple of things to note. The first is, "private Rectangle rect;" and "Rectangle rect = new Rectangle();" are going to be two objects, with the second being local only to the method "canvas1_MouseRightButtonDown". To rectify this, remove the object identifier in the second so it is "rect = new Rectangle();".

The second builds off the first in that you need to have the object initialized before the "MouseMove" event is called. Two thoughts depending upon the version of C#. Put the initialization outside of the methods:
private Rectangle rect = new Rectangle();
In version 4+ there is also something we do in Java to be an inner method, something like:
Rectangle rect = new Rectangle(){
Stroke = Brushes.Black;
StrokeThickness = 1;
}
however, once you have your object created, you can "redo" certain characteristics of the Rectangle in both methods if need be.
 
Share this answer
 
Comments
[no name] 14-Nov-13 12:19pm    
tanks you realy help me!!
greet !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900