UserControl array, each control has a method to set the text of a label there, but getting a NullReferenceException. Help!
So, I create an array:
TorrentItem[] torrents = new TorrentItem[10];
The TorrentItem control has a method called SetTorrentName(string name):
private void SetTorrentName(string Name)
{
label1.Text = Name;
}
I'm using a for loop to po开发者_Python百科pulate 10 TorrentItems like so:
private TorrentItem[] GetTorrents()
{
TorrentItem[] torrents = new TorrentItem[10];
string test = "";
for (int i = 0; i < 10; i++)
{
test = i.ToString();
TorrentItem[i].SetTorrentName(test); //I get a null reference error here.
//What am I doing wrong?
}
You create an array of references to 10 objects, but you do not create the 10 objects in the array. All array elements are null
until initialized otherwise.
for( int i = 0; i < 10; ++i )
{
torrents[i] = new TorrentItem();
/* do something with torrents[i] */
}
However, the name initialization could probably be put into the constructor.
You need to initialize each individual TorrentItem:
for (int i = 0; i < 10; i++)
{
TorrentItem[i] = new TorrentItem(); //Initialize each element of the array
test = i.ToString();
TorrentItem[i].SetTorrentName(test); //I get a null reference error here.
//What am I doing wrong?
}
精彩评论