user222427
user222427

Reputation:

C# Textbox to listbox

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.

Upvotes: 1

Views: 27053

Answers (4)

magnus
magnus

Reputation: 653

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.

Upvotes: 0

Crispy
Crispy

Reputation: 5637

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);
    }

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190935

You might want to do a string Split instead.

string[] items = Regex.Split(textBox2.Text, "\r\n");
listBox1.Items.AddRange(items);

Upvotes: 7

Diadistis
Diadistis

Reputation: 12174

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

Upvotes: 3

Related Questions