0

I try to add two Canvas to a List<Canvas>, but I receive exception from the following code:

List<Canvas> cvList = new List<Canvas>();

Canvas cv = new Canvas();
cv.Width = 100; 
cv.Height = 100;

cvList.Add(cv); // adding first Canvas to List<Canvas>
cvList.Add(cv); // adding the second Canvas to List<Canvas>
...

To elaborate more on the issue, each Canvas has to be distinct since each may Children different TextBox, Label and other UIElement. So I think the above code shouldn't work. However though I cannot do this:

Canvas cv1 = new Canvas();
cv1.Width = 100;
Canvas cv2 = new Canvas();
cv2.Width = 250;
...

Or 

Canvas[] cv = new Canvas[myInt];

I cannot do the above because the size of the List is determine at run time and I cannot assign a size to an Array or declare each array individually.

How to do this correctly? Yes, I've read the List on MSDN, but the site didn't tell me how to do so. Thanks.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
KMC
  • 19,548
  • 58
  • 164
  • 253
  • 1
    You're actually adding the same canvas twice, but this should work just fine. Can you list more code and what the error is that you get? – Matt Greer Apr 04 '11 at 01:48
  • I have elaborate more on the issue and hope that clarify things. – KMC Apr 04 '11 at 02:19

2 Answers2

1

You're adding the same canvas to the list. If you want two different canvases in the list, you have to make two canvases. Note that you can do this with the same variable, just make sure you use the new operator again in between adding them to list.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 1
    The thing is that he/she probably does not really *want* two different canvases but rather that this is a necessity since those elements in the list are quite likely added as visual children somewhere at some point in time. (After all what would the point of a list of UIElements be that connot be seen?) – H.B. Apr 04 '11 at 03:20
1

To elaborate on Joels answer, this is what you need to do:

List<Canvas> cvList = new List<Canvas>();

Canvas canvas1 = new Canvas();
canvas1.Width = 100; 
canvas1.Height = 100;
cvList.Add(canvas1);

Canvas canvas2 = new Canvas();
canvas2.Width = 100; 
canvas2.Height = 100;
cvList.Add(canvas2);

Note that adding the same element twice to the same List<Canvas> collection in this way is perfectly legal, however attempting to use the same element twice in a layout (as might happen depending on the way that this list is used) is not.

Justin
  • 84,773
  • 49
  • 224
  • 367
  • 1
    But adding the same object twice is perfectly legal, it shouldn't lead to an exception. So there is probably more going on here. – Matt Greer Apr 04 '11 at 01:55