简体   繁体   中英

How To Collect all listbox items in a textbox in c#

I have a listbox in which emails are collected in format of example@gmail.com.

I want to transfer these in a text box by clicking a button.

I want the items without "@" and all items splitted by "#".

for example... i have a@mail.com b@mail.com c@mail.com and so on

Now with a button click all items must be in a textbox like a#b#c#.....so on //----------------------------------------------------------------------------------- I know how to transfer all items as it is to textbox.

for(int i = 0; i<listBox1.Items.Count; i++)
{
if((i +1) < listBox1.Items.Count)
textBox1.Text += listBox1.Items[i] + ", ";
else
textBox1.Text += listBox1.Items[i];
}

//---------------------------------------------------------------------------------- How to get all items that are in format of example@mail.com in a textbox without @ and each item separated by #.

Thank you

 foreach (string item in listBox1.Items)
      textBox1.Text += item.Contains("@") ? string.Format("{0}#", item.Split('@')[0]) : string.Empty;

like this?

 public MainWindow()
    {
        InitializeComponent();
        lbSource.Items.Add("example1@yahoo.com");
        lbSource.Items.Add("example2@gmail.com");
        lbSource.Items.Add("example3@hotmail.com");
        lbSource.Items.Add("example4@live.com");


    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        txtShow.Text = "";
        foreach (string item in lbSource.Items)
        {
            string tmp = item.Substring(0, item.IndexOf('@'));
            txtShow.Text += tmp + "#";
        }
    }

try

textBox1.Text="";

for(int i = 0; i<listBox1.Items.Count; i++)
{

textBox1.Text += listBox1.Items[i].toString().Split(new Char [] {'@'})[0] + "#";

}

Here

listBox1.Items[i].toString().Split(new Char [] {'@'})[0] will return only string at the left side of @ in a@mail.com that is a

So the output will be as you intended ie,

example a#b#c#

Use IndexOf method like below

        string output = string.Empty;
        foreach (string email in listBox1.Items)
        {
            int atIndex = email.IndexOf('@');
            output = output + email.Remove(atIndex) + "#";

        }
       textBox1.Text = output;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM