Kevin Sta. Ana
Kevin Sta. Ana

Reputation: 5

Put strings in List<string> and output

I have a test project that puts 4 strings to a list but can't seem to do it right. I am trying to view my list in 2 textboxes using the for and foreach loops.

private void button1_Click(object sender, EventArgs e)
{
    List<string[]> testList2 = new List<string[]>();

    string[] text = { textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text };
    testList2.Add(text);

    textBox5.Text = testList2.Count.ToString();

    foreach (string[] list1 in testList2)
    {
        foreach (string list2 in list1)
        {
            textBox6.Text = list2.ToString();
        }
    }
    string temp = testList2.ToString();
    for (int i = 0; i < testList2.Count; i++)
    {
        for (int j = 0; j < i; j++)
        {
            textBox7.Text = testList2[j].ToString();
        }
    }
}

Upvotes: 0

Views: 549

Answers (1)

Bojan Kogoj
Bojan Kogoj

Reputation: 5649

Without you telling us what your problem is i can only guess that not all values are in textbox that you want. You should use AppendText instead of Text

 private void button1_Click(object sender, EventArgs e)
    {
        List<string[]> testList2 = new List<string[]>();

        String[] text = { textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text };
        testList2.Add(text);

        textBox5.Text = testList2.Count.ToString();

        foreach (string[] list1 in testList2)
        {
            foreach (string list2 in list1)
            {
                textBox6.AppendText(list2);
            }
        }

        for (int i = 0; i < testList2.Count; i++)
        {
            for (int j = 0; j < i; j++)
            {
                textBox7.AppendText(testList2[i][j]);
            }
        }
    }
}

If I am correct what you try to make is a List of strings. If that is so, there is no reason for nesting. Is this what you want?

 private void button1_Click(object sender, EventArgs e)
    {
        List<String> testList2= new List<String>();

        testList2.Add(textBox1.Text);
        testList2.Add(textBox2.Text);
        testList2.Add(textBox3.Text);
        testList2.Add(textBox4.Text);

        textBox5.Text = testList2.Count.ToString();

        foreach (String val in testList2)
        {      
            textBox6.AppendText(val);
        }

        for (int i = 0; i < testList2.Count; i++)
        {
            textBox7.AppendText(testList2[i]);
        }
    }
}

Upvotes: 1

Related Questions