user3565783
user3565783

Reputation:

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

I have a listbox in which emails are collected in format of [email protected].

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 [email protected] [email protected] [email protected] 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 [email protected] in a textbox without @ and each item separated by #.

Thank you

Upvotes: 2

Views: 1751

Answers (4)

Sajad Karuthedath
Sajad Karuthedath

Reputation: 15767

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 [email protected] that is a

So the output will be as you intended ie,

example a#b#c#

Upvotes: 0

Rang
Rang

Reputation: 1372

like this?

 public MainWindow()
    {
        InitializeComponent();
        lbSource.Items.Add("[email protected]");
        lbSource.Items.Add("[email protected]");
        lbSource.Items.Add("[email protected]");
        lbSource.Items.Add("[email protected]");


    }

    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 + "#";
        }
    }

Upvotes: 1

Meysam Tolouee
Meysam Tolouee

Reputation: 579

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

Upvotes: 3

HarisJayadev
HarisJayadev

Reputation: 92

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;

Upvotes: 0

Related Questions