1

I have a listbox being populated from textbox entry.

{
        textBox2.Text.Replace("\r\n", "\r");
        listBox1.Items.Add(textBox2.Text);
    }

Whats happening is the textbox is being populated in a single column format, when it moves over to the listbox the \r\n gets changed to the black squares and does populate the same as it looked in the textbox.

4 Answers 4

7

You might want to do a string Split instead.

string[] items = Regex.Split(textBox2.Text, "\r\n");
listBox1.Items.AddRange(items);
Sign up to request clarification or add additional context in comments.

1 Comment

Doesnt compile. Argument '1': cannot convert from 'string' to 'char[]'
3
listBox1.Items.Add(textBox2.Text.Replace("\r", "").Replace("\n", ""));

4 Comments

this would remove the \r\n, which is not the case, i want to keep the \r\n it's that \r\n gets translated to black squares when moved into the listbox
@Mike those black squares are representing a non-visible character.
i understand, but if i debug it i get.... textBox2 = {Text = "00028\r\n00369\r\n00386\r\n00390\r\n00391\r\n00392\r\n00398
and moving that over to the listbox converts it to black squares
0

Just in case this is helpful to anyone.

If you want all of the text in the textbox to be a single item instead of each line of text being a separate item. You can draw the item yourself.

Example:

    public Form1()
    {
        InitializeComponent();
        listBox1.DrawMode = DrawMode.OwnerDrawVariable;
        listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);
        listBox1.MeasureItem += new MeasureItemEventHandler(listBox1_MeasureItem);      
    }

    void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
    {
        e.ItemHeight = (int)e.Graphics.MeasureString(textBox1.Text, listBox1.Font).Height;
    }

    void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();
        e.DrawFocusRectangle();
        e.Graphics.DrawString(textBox1.Text, listBox1.Font, Brushes.Black, e.Bounds);
    }


    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Add(textBox1);
    }

Comments

0

Do you want the listbox to show the linefeed characters('\r\n')? Do you want the text to appear as one row in the listbox or separate rows for the values 00028, 00039 etc..?

By the way, when I tested i got only the numbers, not the "\r\n", in my listbox. No black squares.

1 Comment

I'm sorry if my "answer" seemed ignorant. I just wanted some things clarified and to inform that i could'n reproduce the error. English isn't my native language so i may sound grumpier than i am.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.