0

I am trying to change the first letter of a string to capital

I saw other questions on this but even when I apply what they've said I still can't manage the correct result.

public string FirstLetterToUpper(string str) { if (str == null) return null; if (str.Length > 1) return char.ToUpper(str[0]) + str.Substring(1); return str.ToUpper(); } private void button1_Click(object sender, EventArgs e) { label1.Text = "test text"; CapitalizeFirstLetter(label1.Text); } 

Instead of outputting

Test text 

it remains

test text 

Any ideas?

3
  • 3
    label1.Text = CapitalizeFirstLetter("test text"); Commented Jan 21, 2015 at 16:22
  • 1
    Do you need to be able to deal with all of unicode? In general you can't take the first UTF-16 code-unit and uppercase it, since one symbol may consist of sever code-units and even several code-points. Commented Jan 21, 2015 at 16:23
  • 1
    Where is the CapitalizeFirstLetter method? If that's implemented in this way everything is fine and should work: label1.Text=FirstLetterToUpper(input); Commented Jan 21, 2015 at 16:23

4 Answers 4

6

You need to assign the result (and use the correct method name)

label1.Text = FirstLetterToUpper("test text"); 
Sign up to request clarification or add additional context in comments.

Comments

1

You're not making use of the return value of your FirstLetterToUpper method. Try this:

private void button1_Click(object sender, EventArgs e) { label1.Text = "test text"; label1.Text = FirstLetterToUpper(label1.Text); } 

Comments

0

I'm not sure if this is a web-based or a desktop-based application. However, I believe your issue stems from a poor deceleration. For instance, your label has a proper value but you aren't reassigning the value.

label1.Text = CapitalizeFirstLetter(label1.Text); 

The reason it isn't working is because you aren't changing the label's value, you leave it as: test text. That is why your issue occurred.

However, you could make it a bit more readable by doing:

label1.Text = CapitalizeFirstLetter("text text"); 

Comments

0

Other answers explain your error (you need to reassign the value obtained by your method to your label), but you could also change the code that capitalizes to use a built-in method

string[] words = label1.Text.Split(); words[0] = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(words[0]); label1.Text = string.Join(" ", words); 

This is more resilient to globalization issues.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.