473,657 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need a hand


I have a form that programmatticly creates 5 labels. Then programatticly
should dispose them, when this happens when it gets down to two lables left
it says that I get a null ref exception.. and I don't know why.

BTW if I check for null it leaves the two labels on my page

Can anyone explain this?

I have included the source code for this very simple test
<code>
using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.Data;
namespace ControlProblem

{

/// <summary>

/// Summary description for Form1.

/// </summary>

public class Form1 : System.Windows. Forms.Form

{

private System.Windows. Forms.Button button1;

private System.Windows. Forms.Button button2;

private System.Windows. Forms.Panel panel1;

/// <summary>

/// Required designer variable.

/// </summary>

private System.Componen tModel.Containe r components = null;

public Form1()

{

//

// Required for Windows Form Designer support

//

InitializeCompo nent();

//

// TODO: Add any constructor code after InitializeCompo nent call

//

}

/// <summary>

/// Clean up any resources being used.

/// </summary>

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Disp ose();

}

}

base.Dispose( disposing );

}

#region Windows Form Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeCompo nent()

{

this.button1 = new System.Windows. Forms.Button();

this.button2 = new System.Windows. Forms.Button();

this.panel1 = new System.Windows. Forms.Panel();

this.SuspendLay out();

//

// button1

//

this.button1.Lo cation = new System.Drawing. Point(48, 296);

this.button1.Na me = "button1";

this.button1.Si ze = new System.Drawing. Size(96, 23);

this.button1.Ta bIndex = 0;

this.button1.Te xt = "Create Controls";

this.button1.Cl ick += new System.EventHan dler(this.butto n1_Click);

//

// button2

//

this.button2.Lo cation = new System.Drawing. Point(248, 296);

this.button2.Na me = "button2";

this.button2.Ri ghtToLeft = System.Windows. Forms.RightToLe ft.No;

this.button2.Si ze = new System.Drawing. Size(112, 23);

this.button2.Ta bIndex = 1;

this.button2.Te xt = "Dispose Controls";

this.button2.Cl ick += new System.EventHan dler(this.butto n2_Click);

//

// panel1

//

this.panel1.Loc ation = new System.Drawing. Point(16, 16);

this.panel1.Nam e = "panel1";

this.panel1.Siz e = new System.Drawing. Size(368, 192);

this.panel1.Tab Index = 2;

//

// Form1

//

this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);

this.ClientSize = new System.Drawing. Size(392, 341);

this.Controls.A dd(this.panel1) ;

this.Controls.A dd(this.button2 );

this.Controls.A dd(this.button1 );

this.Name = "Form1";

this.Text = "Form1";

this.ResumeLayo ut(false);

}

#endregion

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main()

{

Application.Run (new Form1());

}

private void createLabels()

{

int labelLoc = 0;

for(int i=0; i<5; i++)

{

labelLoc += 30;

Label lblDescriptor;

lblDescriptor = new Label();

lblDescriptor.F oreColor = Color.SaddleBro wn;

lblDescriptor.L ocation = new System.Drawing. Point(10 , labelLoc);

lblDescriptor.T extAlign = System.Drawing. ContentAlignmen t.MiddleLeft;

lblDescriptor.N ame = "lbl" + i.ToString();

lblDescriptor.S ize = new System.Drawing. Size(100, 21);

lblDescriptor.T ext = "Test Label 1 " + i.ToString();

this.panel1.Con trols.Add(lblDe scriptor);

}
}

private void button1_Click(o bject sender, System.EventArg s e)

{

createLabels();

}

private void button2_Click(o bject sender, System.EventArg s e)

{

foreach(Control c in this.panel1.Con trols)

{

c.Dispose();

}

}

}

}

</code>

Nov 17 '05 #1
2 1114
You're disposing of objects in the collection so you can't enumerate
through them since they'll be removed from the collection when you do
dispose them. That's why it works for the first 3 but fails on the last
2 (first iteration is index 0 then it's removed so now you really only
have 4 items in your collection, next iteration is index 1 then it's
removed so now you only have 3 items in your collection, etc). In order
to do what you want to do you'll have to start at the end and move
backward.

for(int x = panel1.Controls .Count - 1; x >= 0; x--)
{
panel1.Controls[x].Dispose();
}

Nov 17 '05 #2

Justin Lazanowski wrote:
I have a form that programmatticly creates 5 labels. Then programatticly
should dispose them, when this happens when it gets down to two lables left
it says that I get a null ref exception.. and I don't know why.

BTW if I check for null it leaves the two labels on my page


It does worse than that, it crashes. You just aren't always seeing the
exception. I'm honestly not sure what is going on here, except that
what I *think* happens is that when you dispose of the control from
within the panel control's array, it tells its parent (the panel) to
remove it from the array. Thus, the array changes within the foreach
loop and bad things happen.

Try this:

private void button2_Click(o bject sender, System.EventArg s e)

{
ArrayList al = new ArrayList();

foreach(Control c in this.panel1.Con trols)
{
al.Add( c );
}

foreach( Object o in al )
{
Control c = (Control)o;
c.Dispose();
}
}

It seemed to work ok for me.

Matt

Nov 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
2980
by: Chris Reedy | last post by:
For everyone - Apologies for the length of this message. If you don't want to look at the long example, you can skip to the end of the message. And for the Python gurus among you, if you can spare the time, I would appreciate any comments (including words like evil and disgusting, if you think they are applicable :-}) on the example here. Kenny -
13
2126
by: Roger B. | last post by:
Hello, I am working on a personal interest project and have been racking my brain on this problem for about 5 hours total now, and tracking through old newsgroup posts but haven't figuried it out yet so heres my question. I want to be able to make a list of all possible combinations (repitiions are allowed) of numbers where X is a arbitrary initeger between something like 0 and 100 and the number of x's is arbitrary as well in this...
102
7564
by: RFox | last post by:
I date back to the early days of the web when HTML was limited but very managable, and have always maintained that hand-coding HTML gives you far better control and cleaner HTML markup than any WYSIWYG editor. But all the sites I created and manage are small sites (<50 pages). And I've been out of the loop in terms of what's new in methodology and with the specifications for the past couple of years.
5
2205
by: Rod | last post by:
About two weeks ago I had an accident and have broken my left elbow and left wrist. For doing things like Word or e-mail (I use Outlook for) I have been using Microsoft's speech recognition and that has been working fine. However as a professional programmer I need to be able to type. Right now I can't do that (until my arm heals). I've heard of a program by ScanSoft called Dragon NaturallySpeaking Professional. I called ScanSoft and...
8
1769
by: Ben Fidge | last post by:
Hi I'm working on a site which requires the users to specify a hotel at which they're staying in London. The complete list of hotels comes to something like 1600 records. Each record consists of Hotel Name, Street Address and Postcode. We need to make it as simple as possible for users to pick their hotel, but I don't want to put 1600 hotel names in a drop-down list, and we have to consider the fact that not every user is going to...
2
1946
by: Michael R. Pierotti | last post by:
Dim reg As New Regex("^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$") Dim m As Match = reg.Match(txtIPAddress.Text) If m.Success Then 'No need to do anything here Else MessageBox.Show("You need to enter a valid IP Address", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Hand) txtIPAddress.Focus() Return End If
2
5362
by: michael.rygh | last post by:
This is just one of the sources for a project that deals with a library. I am having problems, here is the errors. all these.. i belive it has something to do with it needs a subscript? but i'm not exactly sure what to do.. (33): error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'char ' (or there is no acceptable conversion) 37): error C2679: binary '>>' : no operator found which takes a
17
1657
by: M.Siler | last post by:
I'm trying to get my head around a conversation I had with a developer the other day. We were talking about Codesmith vs. Hand coding. He's position is Codesmith is for junior to mid level developer who perfer "wizards" to write code for them. That these types of code generators produce substandard developers who don't have real skills. I don't have a position one way or the other until I have a bit more information, but if I was to take...
0
3945
by: U S Contractors Offering Service A Non-profit | last post by:
Brilliant technology helping those most in need Inbox Reply U S Contractors Offering Service A Non-profit show details 10:37 pm (1 hour ago) Brilliant technology helping those most in need Inbox Reply from Craig Somerford <uscos@2barter.net> hide details 10:25 pm (3 minutes ago)
15
2159
by: Jess | last post by:
Hello, Sometimes declarations are all what we need when we define/declare classes (or functions?), but sometimes we need definitions. I learned that if we define a class (B) that has an object (a_obj) of a class type (A), then we need to define A as well, but if B has a pointer to A, then we only need to forward declare A. I was told this is because the compiler needs to see the implemenation of A when allocating memory for a_obj. ...
0
8326
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8845
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7355
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5647
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.