January 6, 2015 by Nitesh

Convert Text to Title Case As You Type in TextBox Control in Windows Forms

Friends,

In this post we will see how can we convert any text written by user in a TextBox Control to Title Case as they type in. If you don’t know about TitleCase, check it on Wikipedia here. In simple words, any sentence where 1st letter of every word is capital is known as to be present in Title Case. To implement this feature in your Windows Forms applications, perform the following steps –

  • Handle the TextChanged event handler of the TextBox
  • Write the below piece of code in the event handler.
         TextBox tb = sender as TextBox;
         tb.Text = Utility.ConvertToTitleCase(tb.Text);
         if (Char.IsUpper(tb.Text.ElementAtOrDefault(tb.Text.Length - 1)))
         {
              tb.SelectionStart = tbPatientComplaintDuration.Text.Length;
              tb.SelectionLength = 0;
         }
    
  • You’re done.

The complete event handler would look like below –

   private void OnTextChanged(object sender,EventArgs e)
   {
     TextBox tb = sender as TextBox;
     tb.Text = Utility.ConvertToTitleCase(tb.Text);
     if (Char.IsUpper(tb.Text.ElementAtOrDefault(tb.Text.Length - 1)))
     {
          tb.SelectionStart = tbPatientComplaintDuration.Text.Length;
          tb.SelectionLength = 0;
     }
   }

Hope this post helps you! Keep learning & sharing! Cheers!

#.Net#C##TextBox#Winforms

Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup