开发者

C# Textbox to listbox

开发者 https://www.devze.com 2022-12-15 11:45 出处:网络
I have a listbox being populated from textbox entry. { textBox2.Text.Replace(\"\\r\\n\", \"\\r\"); listBox1.Items.Add(textBox2.Text);

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 mo开发者_如何学Cves over to the listbox the \r\n gets changed to the black squares and does populate the same as it looked in the textbox.


You might want to do a string Split instead.

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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消