Object reference not set to an instance of an object.
I created several new RichTextBox control at run time and added them to panels contol collection. This is repeated for example 20 times and I get 20 richtextbox control.
for (int i = 0; i < 20;i++)
{
RichTextBox rtb = new RichTextBox();
rtb.Text = i.ToString();
rtb.Visible = false;
rtb.Location = new System.Drawing.Point(72, 72);
rtb.Name = i.ToString(); // So the Name/ID for each will be different.
rtb.Size = new System.Drawing.Size(328, 128);
copyPanel.Controls.Add(rtb);
}
Then I am trying to save the content of each of them to a text file.
foreach (RichTextBox r in copyPanel)
{
r.SaveFile(@"c:\1.txt", RichTextBoxStreamType.PlainText);
}
But it doesn't seem to be working because I get the following exception:
An unhandled exception of type 'System.NullReferenceException' occurred in system.windows.forms.dll
Additional information: Object reference not set to an instance of an object.
What is strange is that when I want to display a message with the contrls name (r.Name;) It seems to be working fine, it just doesn't want to save.
Can someone help me out with this?