Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » VB.NET » Set Text Case with a Custom Control

Set Text Case with a Custom Control

This article shall describe the construction of three custom controls; each is used to format its text content to be either all upper case, all lower case, title case, or normal (as typed) case regardless of the format of the input.

Author Rank :
Page Views : 8437
Downloads : 215
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CaseControlsVBpack.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

This article shall describe the construction of three custom controls; each is used to format its text content to be either all upper case, all lower case, title case, or normal (as typed) case regardless of the format of the input. Such controls may be useful if it is necessary to load the control's text from a source in which the values are in the wrong case; for example, if one were to load a listbox from a column in a database where all of the values were stored as all upper case strings but the desire was to display the text using title case, the Case List control contained in the sample project will make the conversion once the values are loaded into its list.



Figure 1:  The Case Controls in Use.
 

Getting Started

The Case Controls solution contains two projects. The first project is called "CaseControls_VB" and it contains three extended controls (the RichTextBox, the ListBox, and the ComboBox). Each of the controls was extended such that the modified version offered the option of formatting the text contained is the control into one of four options (Upper Case, Lower Case, Normal Case, and Title Case). The second project is called "TestCaseControl_VB" and it is provided to demonstrate use of the controls in a Win Forms application.  



Figure 2:  Solution Explorer with Both Projects Visible.
 

The Case Controls Project

Code:  Case Text

The CaseText control is an extended version of the RichTextBox control; this control was extended such that text sent to the control or keyed directly into it is immediately formatted into one of the four available options (Upper Case, Lower Case, Normal Case, or Title Case). In use, the developer may drop the control onto a form and set a single property "TextCase" that is used by the control to determine how to format the text.

The control is built in a single class entitled "CaseText". The class begins with the following imports and class declaration: 

Imports System

Imports System.Collections

Imports System.ComponentModel

Imports System.Data

Imports System.Drawing

Imports System.Text

Imports System.Windows.Forms

Imports System.Globalization

Imports System.Threading 

 

Public Class CaseText

    Inherits RichTextBox 

The class is declared to inherit from the RichTextBox control. By inheriting from the RichTextBox control, all of the functionality of that control is included. After declaring the class, the next section of code is used to declare an enumeration defining the case mode options, a private member variable used to hold the currently selected text case mode, and a public property used to set or retrieve the selected case mode:

''' <summary>

''' Enumeration of case type options

''' </summary>

''' <remarks></remarks>

Public Enum CaseType

    Normal

    Title

    Upper

    Lower

End Enum 

 

''' <summary>

''' Set the current case type for the control;

''' default to normal case

''' </summary>

''' <remarks></remarks>

Private mCaseType As CaseType = CaseText.CaseType.Normal 


''' <summary>

''' property used to maintain current case type

''' </summary>

''' <value></value>

''' <returns></returns>

''' <remarks></remarks>

Public Property TextCase() As CaseType

    Get

        Return mCaseType

    End Get

    Set(ByVal value As CaseType)

        mCaseType = value

    End Set

End Property 

The next block of code contains the default constructor; since this control is intended to serve as either a textbox or a richtextbox, the control's constructor contains a bit of code to make the control look more like a standard textbox control when it is created (the multi-line property is set to false and the height is set to 20). The initialize component method also includes the addition of a text changed event handler: 

''' <summary>

''' Default constructor

''' </summary>

''' <remarks></remarks>

Public Sub New()

    ' This call is required by the Windows Form Designer.

    InitializeComponent()

 

    Me.Text = String.Empty

    Me.Multiline = False

    Me.Height = 20

End Sub 

The last bit of code required by the control is the text changed event handler which is used merely to call a method used to update the case of the text based upon the selected case mode property. Since this method is called whenever text changed event fires, the textbox will update the case as the user types. When the UpdateTextCase method is called, the method stores the text currently contained in the control and it stores the position of the insert cursor. The copy of the text placed in the string varible is operated on within the method and then is used to replace the text contained in the control. The position of the insert is stored so that the cursor may be restored to its original position after the text has been replaced. This supports edits made to sections of the string other than the end or beginning of the string.

''' <summary>

''' Call the Update Text Case function each time

''' the text changes

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub CaseText_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.TextChanged

    UpdateTextCase()

End Sub 

 

''' <summary>

''' Depending upon the Case Type selected,

''' process the textbox accordingly

''' </summary>

''' <remarks></remarks>

Private Sub UpdateTextCase()

 

    Dim sControlText As String = Me.Text

    Dim cursorPosition As Integer = Me.SelectionStart

 

    Select Case (Me.TextCase)

        Case CaseType.Lower

            ' convert to all lower case

            Me.Text = Me.Text.ToLower()

        Case CaseType.Normal

            ' do nothing

        Case CaseType.Title

            ' convert to title case

            Dim sTemp As String = Me.Text.ToLower()

            Dim ci As CultureInfo = Thread.CurrentThread.CurrentCulture

            Dim ti As TextInfo = ci.TextInfo

            Me.Text = ti.ToTitleCase(sTemp)

        Case CaseType.Upper

            ' convert to all upper case

            Me.Text = Me.Text.ToUpper()

        Case Else

            ' there is nothing else

    End Select

 

    ' Move to the correct position in the string

    Me.SelectionStart = cursorPosition

 

End Sub 

 

The code used in the CaseList and CaseCombo controls is very similar and is all included in the download; for that reason I won't describe it here in this document. The only major difference between the code used in those controls is that the Update Text methods are made public in the list controls so that the user may evoke the method whenever the list is created or changed.  Whenever the user evokes the method, the update method will loop through the text in the collection and update the case of each list item. 

Code:  Test Case Control

This project is used to test the custom controls. The project contains a single Windows form. The form contains four of each type of custom control, each of which is intended to demonstrate one of the case mode options. 

The form class begins with the default class declaration:

Public Class Form1

 

In the form load event handler, the list type controls are all populated manually using strings formatting contrary to what is desired for display. For example, the if the custom listbox control is set to display upper case text, the text submitted to the control's list is passed in using lower case or mixed case strings. After each list is loaded, the controls update text case method is evoked to reformat the case used in the list items:

Private Sub Form1_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

 

    ' C O M B O  B O X  E X A M P L E

    '

    ' load an Upper Case list with these items

    CaseCombo1.Items.Add("popeye")

    CaseCombo1.Items.Add("olive oil")

    CaseCombo1.Items.Add("brutus")

    CaseCombo1.Items.Add("whimpy")

    CaseCombo1.Items.Add("sweet pea")

    ' update the case of these list items

    CaseCombo1.UpdateListTextCase() 

 

    ' load a Lower Case list with these items

    CaseCombo2.Items.Add("CHOCOLATE CREAM")

    CaseCombo2.Items.Add("Rasberry Truffle")

    CaseCombo2.Items.Add("PINEAPPLE Sling")

    CaseCombo2.Items.Add("COCONUT HEaRt")

    CaseCombo2.Items.Add("VANILLA ICE Cream")

    ' update the case of these list items

    CaseCombo2.UpdateListTextCase() 

 

    ' load a Normal Case list with these items

    CaseCombo3.Items.Add("George S. Patton")

    CaseCombo3.Items.Add("Mikhail Miloradovich")

    CaseCombo3.Items.Add("Bernard Montgomery")

    CaseCombo3.Items.Add("Carl von Clausewitz")

    CaseCombo3.Items.Add("Sun Tzu")

    ' update the case of these list items

    CaseCombo3.UpdateListTextCase() 

 

    ' load a Title Case list with these items

    CaseCombo4.Items.Add("john lennon")

    CaseCombo4.Items.Add("paul mc cartney")

    CaseCombo4.Items.Add("ringo starr")

    CaseCombo4.Items.Add("george harrison")

    CaseCombo4.Items.Add("peter best")

    ' update the case of these list items

    CaseCombo4.UpdateListTextCase() 

 

    ' L I S T  B O X  E X A M P L E

    '

    ' load an Upper Case list with these items

    CaseList1.Items.Add("popeye")

    CaseList1.Items.Add("olive oil")

    CaseList1.Items.Add("brutus")

    CaseList1.Items.Add("whimpy")

    CaseList1.Items.Add("sweet pea")

    ' update the case of these list items

    CaseList1.UpdateListTextCase() 

 

    ' load a Lower Case list with these items

    CaseList2.Items.Add("CHOCOLATE CREAM")

    CaseList2.Items.Add("Rasberry Truffle")

    CaseList2.Items.Add("PINEAPPLE Sling")

    CaseList2.Items.Add("COCONUT HEaRt")

    CaseList2.Items.Add("VANILLA ICE Cream")

    ' update the case of these list items

    CaseList2.UpdateListTextCase() 

 

    ' load a Normal Case list with these items

    CaseList3.Items.Add("George Patton")

    CaseList3.Items.Add("Mikhail Miloradovich")

    CaseList3.Items.Add("Bernard Montgomery")

    CaseList3.Items.Add("Carl von Clausewitz")

    CaseList3.Items.Add("Sun Tzu")

    ' update the case of these list items

    CaseList3.UpdateListTextCase() 

 

   ' load a Title Case list with these items

    CaseList4.Items.Add("john lennon")

    CaseList4.Items.Add("paul mc cartney")

    CaseList4.Items.Add("ringo starr")

    CaseList4.Items.Add("george harrison")

    CaseList4.Items.Add("peter best")

    ' update the case of these list items

    CaseList4.UpdateListTextCase()

 

End Sub 

The only other code in the form class are a set button event handlers that will pass an improperly formatted string to each of the four custom case text controls: 

Private Sub btnToUpper_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnToUpper.Click

 

    CaseText1.Text = Me.lblToUpperCase.Text

 

End Sub 

 

Private Sub btnToLower_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnToLower.Click

 

    CaseText2.Text = Me.lblToLowerCase.Text

 

End Sub 

 

Private Sub btnToNormal_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnToNormal.Click

 

    CaseText3.Text = Me.lblToNormalCase.Text

 

End Sub 

 

Private Sub btnToTitle_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnToTitle.Click

 

    CaseText4.Text = Me.lblToTitleCase.Text

 

End Sub 

Summary.

This article was intended to demonstrate an approach to building a set of custom controls that could be used to reformat the case of the text or list item text; the purpose of such a control would be to allow improperly formatted text obtained from an external source to be properly displayed in the context of a Windows application without the need to modify the source of text.  Such a control may be useful if one is, for example, attempting to display data obtained from a database that is not stored in the proper format (e.g., the column contains all upper case strings but the desire is to display it as title case strings or all lower case string).

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.