C#文本框到列表框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1969720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:18:03  来源:igfitidea点击:

C# Textbox to listbox

c#

提问by

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.

发生的事情是文本框以单列格式填充,当它移到列表框时,\r\n 会更改为黑色方块,并且填充的内容与它在文本框中的外观相同。

采纳答案by Daniel A. White

You might want to do a string Splitinstead.

你可能想要做一个字符串Split

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

回答by Diadistis

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

回答by Chris Persichetti

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

回答by magnus

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..?

你想让列表框显示换行符('\r\n')吗?您希望文本显示为列表框中的一行还是值 00028、00039 等的单独行?

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

顺便说一下,当我测试时,我的列表框中只有数字,而不是“\r\n”。没有黑色方块。