Array af controller
jeg har via http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkArraysTutorial.asplave flg. kode
LabelArray.cs indholder :
/*
* Created by SharpDevelop.
* User: Thomas
* Date: 13-10-2006
* Time: 10:18
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace lotto
{
/// <summary>
/// Description of LabelArray.
/// </summary>
public class LabelArray : System.Collections.CollectionBase
{
private readonly System.Windows.Forms.Form HostForm;
public System.Windows.Forms.Label AddNewLabel()
{
// Create a new instance of the Button class.
System.Windows.Forms.Label aLabel = new System.Windows.Forms.Label();
// Add the button to the collection's internal list.
this.List.Add(aLabel);
// Add the button to the controls collection of the form
// referenced by the HostForm field.
HostForm.Controls.Add(aLabel);
// Set intial properties for the button object.
aLabel.Top = Count * 25;
aLabel.Left = 100;
aLabel.Tag = this.Count;
aLabel.Text = "Label " + this.Count.ToString();
aLabel.Click += new System.EventHandler(ClickHandler);
return aLabel;
}
public LabelArray(System.Windows.Forms.Form host)
{
HostForm = host;
this.AddNewLabel();
}
public System.Windows.Forms.Label this [int Index]
{
get
{
return (System.Windows.Forms.Label) this.List[Index];
}
}
public void Remove()
{
// Check to be sure there is a button to remove.
if (this.Count > 0)
{
// Remove the last button added to the array from the host form
// controls collection. Note the use of the indexer in accessing
// the array.
HostForm.Controls.Remove(this[this.Count -1]);
this.List.RemoveAt(this.Count -1);
}
}
public void ClickHandler(Object sender, System.EventArgs e)
{
System.Windows.Forms.MessageBox.Show("You have clicked label " + ((System.Windows.Forms.Label) sender).Tag.ToString());
}
}
}
og i min knap
void Command1Click(object sender, System.EventArgs e)
{
byte xtel;
//int atel;
for(xtel=1;xtel<7;xtel++)
{
MyControlArray.AddNewLabel();
MyControlArray[(xtel-1)].BackColor = System.Drawing.Color.Red;
locX += this.r.Width+20;
}
}
men når jeg klikker på knappen får jeg flg. fejl
Exception System.NullReferenceException was thrown in debuggee:
Object reference not set to an instance of an object.
Command1Click() - c:\Documents and Settings\Thomas\Dokumenter\SharpDevelop Projects\lotto\MainForm.cs:63,5
OnClick()
OnClick()
OnMouseUp()
WmMouseUp()
WndProc()
WndProc()
WndProc()
OnMessage()
WndProc()
DebuggableCallback()
System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop()
RunMessageLoopInner()
RunMessageLoop()
Run()
Main() - c:\Documents and Settings\Thomas\Dokumenter\SharpDevelop Projects\lotto\MainForm.cs:27,4
og denne linje bliver gul
MyControlArray.AddNewLabel();
når jeg siger den skal break;
