Home > Enterprise >  Assign labels text to a string array
Assign labels text to a string array

Time:11-16

enter image description hereI'm developing a quiz game for college .

What I want is to stock all of the 8 label.Text values into an array , or in anything that I can itterate through.

string[] raspunsuri = new string[8] { label2.Text , label3.Text , etc ...};

Error code is : CS0236. I'm new to C# and even googling things up didn't help me much .

I tried declaring a single value at a time

string test = label.text;

but I get the same error. Tried declaring inside a public method I created but it doesn't work either.

CodePudding user response:

Can you post your full code?

I'm assuming you are using WinForms, or something similar where you are getting text from label.

I would guess that you may not be writing this code inside a method. Try writing this code for initializing your array inside of a method. Your error code points to that you are trying to write this code outside of a method or function. Instead of

string[] raspunsuri = new string[8] { label2.Text , label3.Text , etc ...};

Try

static void Main(string[] args)
{
    string[] raspunsuri = new string[8] { label2.Text , label3.Text , etc ...};
}

Or you can put it in any method that you would like.

Hope that helps!

CodePudding user response:

There are several possibilities. If labels can change their Texts I suggest implementing a property to get fresh values:

// Read-only property: whenever you read it, 
// it creates and return an array with fresh values
string[] raspunsuri => new string[] { label2.Text, label3.Text, etc ...};

If labels don't change their values, you should declare string[] Raspunsuri field, but assign values later; assuming that you have WinForms it can be something like this:

public partial class MyForm : Form 
{
    string[] raspunsuri;

    ...

    public MyForm()
    {
        // Let labels be created and obtain their values
        InitializeComponent();

        // Time to assign values to the field
        raspunsuri = new string[] { label2.Text, label3.Text, etc ... };  
    }

    ...
}

Same with just one label: just try property:

string test => label.Text;
  •  Tags:  
  • c#
  • Related