Reputation: 91
i have a multiline textbox which has comma separated value e.g: java,sql,php i want all text items to be moved to listbox on click of a add button mu desired output : java sql php
StringBuilder bulder = new StringBuilder();
string[] oldstring = { TextBox1.Text};
foreach (string str in oldstring)
{
bulder.Append(str);
bulder.Append(",");
}
string[] newstring = bulder.ToString().Split(',');
TextBox1.Text = bulder.ToString().TrimEnd(',');
by using this code am getting values as java,sql,php only what am doing wrong here?
Upvotes: 0
Views: 1143
Reputation: 6075
You are not splitting the TextBox1.Text
correctly: you're not reading each line as a separate string
. You are reading the entire string and then splitting it.
You can accomplish what you are asking much more simply. This is a simple version of what I believe you're trying to do, and it could even be simplified further if desired.
private void button1_Click(object sender, EventArgs e)
{
string[] oldString = TextBox1.Text.Split(
new string[]{","},
StringSplitOptions.RemoveEmptyEntries);
ListBox1.Items.AddRange(oldString);
}
This is a button click event that splits the text from TextBox1
by ,
characters, then adds each item to ListBox1
using the Items.AddRange(string[] items)
method.
If we wanted to manually update the listbox one item at a time instead, we can use a foreach
loop instead.
private void button1_Click(object sender, EventArgs e)
{
string[] oldString = TextBox1.Text.Split(
new string[]{","},
StringSplitOptions.RemoveEmptyEntries);
foreach (string item in oldString)
{
ListBox1.Items.Add(item);
}
}
Upvotes: 1