C# Windows Forms - Weird multiline textbox behaviour

I am using a StringReader to read input from a multi-line textbox. However, I am experiencing strange behaviour.
My Code:

string x = reader.ReadLine();
int y = int.Parse(x);

x is always an int.
My problem is that since x is the first line of the multiline textbox, it doesn't contain just the int, but System.Windows.Forms.Textbox, Text:10
Any help here?

I create the StringReader as following:

using (StringReader reader = new StringReader(Convert.ToString(multilinetbox)))
{

}

Upvotes: 1

Views: 890

Answers (5)

Anton Semenov
Anton Semenov

Reputation: 6347

You have normal results for your code, because Convert.ToString(multilinetbox) converts it to text representation.

Try to user 'Lines' property instead:

foreach (string ln in textBox1.Lines)
{
    // some work here
}

Upvotes: 0

Wang Xiong
Wang Xiong

Reputation: 1

Because Convert.ToString(multilinebox) first converts the type information, and then get the text content.

You should change the multilinebox to multilinebox.Text.

Like

using (StringReader reader = new StringReader(Convert.ToString(multilinetbox.Text)))
{    
}

Upvotes: 0

jAC
jAC

Reputation: 5324

This should work:

    private void button1_Click(object sender, EventArgs e)
    {
        StringReader rdr = new StringReader(textBox1.Text);
        int y = int.Parse(rdr.ReadLine());
    }

I think you made a mistake at your StringReader declaration.

Upvotes: 0

Sandy
Sandy

Reputation: 11687

I know you are not asking this but still I thought to post it.

Why not try

foreach (string line in multilinetbox.Lines)
{
    int y = int.Parse(line);
}

Hope it helps.

Upvotes: 0

Blachshma
Blachshma

Reputation: 17385

Change your reader to read the Text property of the multiline textbox, instead of the entire control:

using (StringReader reader = new StringReader(multilinetbox.Text))

Upvotes: 5

Related Questions