LightSwitch Upper Case in TextBoxes.

How to uppercase text entered into a textbox by a user?


Handle the KeyUp event.


Imagine you have a NewClient screen and want to upper the text entered in a property called “Name”.

In NewClient.cs

partial void NewClient_InitializeDataWorkspace(global::System.Collections.Generic.List saveChangesTo)
   this.FindControl("Name").ControlAvailable += TextBoxAvailable;
   // Write your code here.

   this.ClientProperty = new Client();

private void TextBoxAvailable(object sender, ControlAvailableEventArgs e)
   ((System.Windows.Controls.TextBox)e.Control).KeyUp += TextBoxKeyUp;

private void TextBoxKeyUp(object sender, System.Windows.RoutedEventArgs e)
   var textbox = (System.Windows.Controls.TextBox)sender;

   string textUppered = textbox.Text.ToUpper();
   int selStart = textbox.SelectionStart;
   textbox.Text = textUppered;
   textbox.SelectionStart = selStart;

Source: Pro Visual Studio LightSwith 2011 Development by Tim Leung and Yann Duran, Apress


The previous code has a drawback, when you entered the text you can see how the text gets uppered, like an animation. To correct this behaviour handle the KeyDown event instead.

Here is a new version:

public partial class NewClient
   partial void NewClient_Activated()
      this.FindControl("Name").ControlAvailable += TextBoxAvailable;
      // Write your code here.

      this.ClientProperty = new Client();

   private void TextBoxAvailable(object sender, ControlAvailableEventArgs e)
      ((System.Windows.Controls.TextBox)e.Control).KeyDown += TextBoxKeyDown;

   private void TextBoxKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
      var textbox = (System.Windows.Controls.TextBox)sender;

      if (e.Key >= System.Windows.Input.Key.A && e.Key <= System.Windows.Input.Key.Z)
         int selStart = textbox.SelectionStart;
         if (textbox.SelectionLength > 0)
            string str1 = textbox.Text.Remove(textbox.SelectionStart, textbox.SelectionLength);
            textbox.Text = str1.Insert(selStart, e.Key.ToString()).ToUpper();
            textbox.Text = textbox.Text.Insert(selStart, e.Key.ToString()).ToUpper();
         textbox.SelectionStart = selStart + 1;
         e.Handled = true;

Note: Still there is a flaw, if you paste from the Clipboard text in lowered case, it doesn’t work.

This entry was posted in LightSwitch and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s