Reputation: 1784
I have an text box and I want split its text and print that splited text in different labels. suppose I text box user writes Ravi Bhushan now I want spit it in two labels each after the space (In first label Ravi and in second label Bhushan. In ASP.net using c#
protected void btnSubmit_Click(object sender, EventArgs e)
{
string Name = txtName.Text.ToString();
char[] seperators = new char[] {' '};
string[] splitedName = Name.Split(seperators);
foreach (string s in splitedName)
{
//System.Console.WriteLine(s);
lblFst.Text = s.ToString();
}
}
If I use above code then in LblFst where I want to print Ravi it is printing Bhushan
Upvotes: 0
Views: 798
Reputation: 7943
You can do like this:
protected void btnSubmit_Click(object sender, EventArgs e)
{
// string Name = txtName.Text.ToString();
//char[] seperators = new char[] {' '};
string[] splitedName = txtName.Text.Split(' ');
lblFst.Text = splitedName[0];
lblSecond.Text = splitedName[1];
}
To prevent XSS attack, you should encode the string before assigning them to label:
lblFst.Text = HttpUtility.HtmlEncode(splitedName[0]);
lblSecond.Text = HttpUtility.HtmlEncode(splitedName[1]);
Thanks to Michael Liu for pointing to this!
Upvotes: 1