KayBay
KayBay

Reputation: 749

C# Initialising an array of labels "Cannot implicitly convert 'string' to 'System.Windows.Forms.Label'

I have a member variable declared as follows:

private Label[] dice = new Label[numberOfDice];

and when I try to initialize the values within dice with labels on my form I get the error "Cannot implicitly convert 'string' to 'System.Windows.Forms.Label'" in this line:

dice[i] = dieName;

I understand that dieName is a string but the dice array wants me to provide it with the name of an actual label in my form. In my form, I have five labels named die1, die2, ..., die5.

Here is the function where I am initializing the dice array:

private void InitializeLabels()
{
   for (int i = 0; i < numberOfDice; i++)
   {
       string dieName = String.Format("die{0}", i + 1);
       dice[i] = dieName;
   }
}

I know I could just do this:

dice[0] = die1;
dice[1] = die2;
...
dice[4] = die5;

but I would like to use a cleaner method like the for-loop above.

Upvotes: 1

Views: 288

Answers (2)

Alastair Brown
Alastair Brown

Reputation: 1616

Try this:

private void InitializeLabels()
{
   for (int i = 0; i < numberOfDice; i++)
   {
       string dieName = String.Format("die{0}", i + 1);
       dice[i].Text = dieName;
   }
}

or if they aren't initialised

private void InitializeLabels()
{
   for (int i = 0; i < numberOfDice; i++)
   {
       string dieName = String.Format("die{0}", i + 1);
       dice[i].Text = new Label{Parent = this, 
                                Text = dieName, 
                                Size = new Size(50,20), 
                                Location = new Point(i * 50, 0)};
   }
}

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29006

From the error message it is clear that you are assigning a string type value(dieName) to a variable of type Label so you met with such error. I think you are trying to set the value of the Label Text, if so you should use the .Text property of the Label Control. If you want to give a name for the Label means you should use the .Name property, Now you can take a look into the snippet to achieve the target.

for (int i = 0; i < numberOfDice; i++)
{
    string dieName = String.Format("die{0}", i + 1);
    dice[i].Text = dieName;
    dice[i].Name = dieName;
}

Upvotes: 1

Related Questions