I've been trying to figure this out for a while. I have some code that looks like this:
PictureBox p = null;
PictureBox pb_dice = null;
for(int i = 1l I < 7; i++)
{
p = this.Controls["p" + i.ToString()] as PictureBox;
pb_dice = this.Controls["p_dice" + i.ToString()] as PictureBox;
p.Image = WindowsFormsApplication1.Properties.Resources.diceBlank;
pb_dice.Image = WindowsFormsApplication1.Properties.Resources.diceBlank;
}
When I run it, I get an error "Object reference not set to an instance of an object." for the pb_dice.Image, but the p.Image works fine. The resource diceBlank.png is valid and I double-
checked that both Pictureboxes are indeed pictureboxes. Both pictureboxes properties are identical and neither are part of a group or panel.
I'm using Visual Studio C# 2010 Express.
Any suggestions?
Loading
Sam HobbsPosted Nov 6, 2010, 11:21 PM
So at least my suggestion to check for null was relevant; also checking to ensure that there really is a control with the expected id. I know that problems such as that happen.
Sam HobbsPosted Nov 7, 2010, 1:05 AM
Jerry FikePosted Nov 6, 2010, 11:52 PM
What also helped me was a tool I hadn't noticed before. In the debug watch window I noticed a little "Text Visualizer" icon in the view column. I clicked on it and saw "p_dice1" (instead of "pb_dice") and then it hit me.
Jerry FikePosted Nov 6, 2010, 11:12 PM
I looked and looked at that code and didn't see the obvious.
pb_dice = this.Controls["p_dice" + i.ToString()] as PictureBox;
|
|
should be "pb_dice"
That's what I get for "copying and pasting" to save time. I had a bunch of Pictureboxes named p1, p2
p3, etc. I would usually use pb_1, pb_2, etc, but there were so many it was easier using the shorter name. Then when I created pb_dice1, 2, etc., I copied the p1, p2 ... code with the intent of modifying the names. Of course I missed the "pb" part!
Thanks for your help and sorry I took up your time.
Sam HobbsPosted Nov 5, 2010, 11:59 PM
Jerry FikePosted Nov 5, 2010, 11:22 PM
the picturebox dice are pb_dice1 thru pb_dice6. Sure, I could reference them as "pb_dice " + i+1ToString(), but it seems it's a little easier to understand the way I did it (and besides, I did the same thing for p.Image.)
[I see what you mean -- I made a mistake when I posted the first message. The code is really
for(int i = 1; i < 7; i++), not for(int i = 1l I < 7; i++). Not sure how that "|" got in there, and actually the p.Image wouldn't work under that code. I made the mistake typing in the message, not in the actual code.]
It errors on the first iteration of the for loop (i = 1).
Sam HobbsPosted Nov 5, 2010, 11:00 PM
Also, are you totally sure you posted the correct code? If so, then are you sure you looked closely at it? The code you posted is wrong; you don't want to set i to "1l I < 7".