JordonG JordonG - 1 month ago 10
C# Question

Adding String Values to an Array

I have this piece of code and this may seem like a very stupid question but it is they way I was taught to do it and it is not working correctly for me.

I wanted it to be that when I entered text into the txtEnterWord text box it would be added to the array "words" and displayed in the list box lstWords but every time I go to add a second word it clears the previous word and replaces it with the new one. Anyone know how to fix this? :)

private void btnEnter_Click(object sender, EventArgs e)
{
//string[] words = new string[6];
//words[6] = txtEnterWord.Text;

//for (int i = 0; i < words.Length; i++)
//{
// lstWords.Items.Add(words[i]);
//}

lstWords.Items.Clear();
string[] words = new string[6];

//words[0] = txtEnterWord.Text;
//words[1] = txtEnterWord.Text;
//words[2] = txtEnterWord.Text;
//words[3] = txtEnterWord.Text;
//words[4] = txtEnterWord.Text;
//words[5] = txtEnterWord.Text;

for (int i = 0; i < words.Length;i++)
{
//words[i] = txtEnterWord.Text;
lstWords.Items.Add(txtEnterWord.Text);
txtEnterWord.Clear();
//lstWords.ToString() = lstWords.ToString() + words[i].ToString();
}

Answer

It should just be the below code. No need for a for loop and you shouldn't be clearing lstWords.Items because that is why your data is disappearing. Just add the textbox Text to your list and then clear the textbox. You also don't need the string[] words because it is doing nothing as a local variable. If you really wanted to add it to a string[] then it would need to be a member of the class this method is in. I think just doing lstWords.Items.Add should be good though if that's where you need the text to be saved.

private void btnEnter_Click(object sender, EventArgs e)
{
    lstWords.Items.Add(txtEnterWord.Text);
    txtEnterWord.Clear();
}
Comments