5

I am creating a dynamic array, and getting an error:

Error message: Cannot convert type 'string' to 'string[]'

The code is:

arrTeamMembers += tb.Text;

tb.Text contains values such as Michael | Steve | Thomas | Jeff | Susan | Helen |

I am trying to pass the values from tb.Text to arrTeamMembers. I am NOT trying to split the text.

How can I resolve this error?

5
  • What do you exactly mean by "pass the values from tb.Text to arrTeamMembers"? Does arrTeamMembers already have items in it? Commented Feb 25, 2010 at 22:14
  • no, arrTeamMembers is empty / null Commented Feb 25, 2010 at 22:15
  • Are you wanting to set arrTeamMembers to the individual values in tb.Text? E.g. [Michael, Steve, Thomas, ...] Commented Feb 25, 2010 at 22:17
  • No, I want arrTeamMembers to contain "Michael | Steve | Thomas | Jeff | Susan | Helen |" Commented Feb 25, 2010 at 22:20
  • If you want the first item to be the value of tb.Text then you need to set it as jdmx and David Menton suggested. Commented Feb 25, 2010 at 22:23

4 Answers 4

12

You can't just add strings to an array of strings.

Depending on what you are actually trying to do, you might want this:

string[] arrTeamMembers = new string[] { tb.Text };

or

arrTeamMembers[0] = tb.Text;

You probably want to use a List instead.

List<string> stringlist = new List<string>();
stringlist.Add(tb.Text);
Sign up to request clarification or add additional context in comments.

Comments

10

Try this:

arrTeamMembers = tb.Text.Split('|');

Comments

8

The problem is, arrTeamMembers is an array of strings, while tb.Text is simply a string. You need to assign tb.Text to an index in the array. To do this, use the indexer property, which looks like a number in square brackets immediately following the name of the array variable. The number in the brackets is the 0-based index in the array where you want to set the value.

arrTeamMembers[0] += tb.Text;

2 Comments

Did you mean the += to be an =?
No, I was using the same operator the OP used.
1

If you are trying to split the text in the textbox then

arrTeamMembers = tb.Text.Split( '|' );

If this does not work, are you trying to append the textbox to the end of the array?

if ( arrTeamMembers == null )
  arrTeamMembers  = new string[0];

string[] temp = new string[arrTeamMembers.Length + 1];
Array.Copy( temp , 0, arrTeamMembers, 0, arrTeamMembers.Length );
temp[temp.Length - 1] = tb.Text;
arrTeamMembers = temp;

3 Comments

I am trying to pass the values from tb.Text to arrTeamMembers. I am not trying to split the text.
so you want? string [] arrTeamMembers = new string[1]; arrTeamMembers[0] = tb.Text;
or you want something like this: string [] arrTeamMembers = {tb.Text}; which is the same as jdmx's (i.e. create an array of one element).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.