0

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

0

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.