The TextBox Widget

IronPython & Windows Forms, Part V

Windows Forms

Note

This is part of a series of tutorials on using IronPython with Windows Forms.

 

 

Introduction

It's time to cover some more interesting widgets. In this entry we're going to look at the TextBox. The TextBox allows you to receive text input from the user. It is most useful for single lines of text. For multiple lines of text, you will probably want to use the RichTextBox.

It's a very easy to use widget, so hopefully this entry will be short. Smile

Getting started with the TextBox is no different to the other widgets we've used so far. The Microsoft documentation provides the following example :

TextBox textBox1 = new TextBox();

Again, the TextBox constructor is called with no arguments. Like the other widgets we've used, we can get or set the Text property to access the contents of the TextBox. All trivially easy. In fact it doesn't really get more complicated, but if we stopped here there would still be something missing. In a normal Windows application when you press enter in a textbox the application will perform an action.

Windows Forms applications have two special keys. These are Enter and Esc. Enter (or Return) is the same as an Accept action, and Esc (Escape) is the same as a Cancel action. We can bind these two actions to buttons. Let's make our example have two buttons.

  1. The first button will take the text from a textbox and display it in a label. This can be the accept button.
  2. The second button will reset the textbox, this can be the cancel button.

To do this we need to set the AcceptButton and CancelButton properties on the form.

The accept and cancel actions belong to the form, so if you want to have different actions for different widgets [1] you'll have to catch (and handle) the event before it gets to the form. We'll cover all that when we get to events in another entry.

The full code for our simple example looks like this :

import clr
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')

from System.Drawing import Point
from System.Windows.Forms import Application, Button, Form, Label, TextBox

class SimpleTextBoxForm(Form):
    def __init__(self):
        self.Text = "Simple TextBox Example"

        self.Width = 300
        self.Height = 200

        self.label = Label()
        self.label.Text = "Nothing So Far"
        self.label.Location = Point(25, 25)
        self.label.Height = 25
        self.label.Width = 250

        self.textbox = TextBox()
        self.textbox.Text = "The Default Text"
        self.textbox.Location = Point(25, 75)
        self.textbox.Width = 150

        self.button1 = Button()
        self.button1.Text = 'Press Me'
        self.button1.Location = Point(25, 125)
        self.button1.Click += self.update

        self.button2 = Button()
        self.button2.Text = 'Reset'
        self.button2.Location = Point(125, 125)
        self.button2.Click += self.reset

        self.AcceptButton = self.button1
        self.CancelButton = self.button2

        self.Controls.Add(self.label)
        self.Controls.Add(self.textbox)
        self.Controls.Add(self.button1)
        self.Controls.Add(self.button2)

    def update(self, sender, event):
        self.label.Text = self.textbox.Text

    def reset(self, sender, event):
        self.label.Text = "Nothing So Far"
        self.textbox.Text = "The Default Text"

form = SimpleTextBoxForm()
Application.Run(form)

When you run this program, this is what you'll see :

Simple TextBox Example

and :

Simple TextBox Example

OnMono this will look like :

Simple TextBox Example

and :

Simple TextBox Example

Multiline TextBox

The TextBox has several properties that affect its behaviour and appearance. Fortunately Microsoft (in their munificence) have provided us with a useful example of how to use some of them :

// Set the Multiline property to true.
textBox1.Multiline = true;
// Add vertical scroll bars to the TextBox control.
textBox1.ScrollBars = ScrollBars.Vertical;
// Allow the RETURN key to be entered in the TextBox control.
textBox1.AcceptsReturn = true;
// Allow the TAB key to be entered in the TextBox control.
textBox1.AcceptsTab = true;
// Set WordWrap to True to allow text to wrap to the next line.
textBox1.WordWrap = true;
// Set the default text of the control.
textBox1.Text = "Welcome!";

Most of this is straightforward. If we turn this example directly into Python we will get a multiline textbox with a vertical scrollbar. It allows the RETURN key and TAB key to be entered into the text box without triggering the AcceptButton or moving to the next widget [2]. It will even have wordwrap enabled.

You can browse the TextBox Members documentation to see what all of these properties are and what they do.

The new thing in the example above is the scrollbar. The TextBox.ScrollBars Property takes a System.Windows.Forms.Scrollbars Enumeration value to set which scrollbars are active for the textbox. Possible values (members of the enumeration) are :

  • Both Both horizontal and vertical scroll bars are shown.
  • Horizontal Only horizontal scroll bars are shown.
  • None No scroll bars are shown.
  • Vertical Only vertical scroll bars are shown.

There is a note on the TextBox.ScrollBars property that says :

Horizontal scroll bars will not be shown if the WordWrap property is set to true, regardless of the value of the ScrollBars property.

Worth knowing. Smile

We'll create a second example. This one will dump the contents of the textbox to the console when you press the button.

import clr
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')

from System.Drawing import Point
from System.Windows.Forms import (Application, Button, Form, ScrollBars,
    TextBox)

class MultilineTextBoxForm(Form):
    def __init__(self):
        self.Text = "Multiline TextBox"

        self.Width = 250
        self.Height = 200

        self.setupTextBox()

        def update(sender, event):
            print self.textbox.Text

        self.button1 = Button()
        self.button1.Text = 'Press Me'
        self.button1.Location = Point(20, 125)
        self.button1.Click += update

        self.button2 = Button()
        self.button2.Text = 'Reset'
        self.button2.Location = Point(125, 125)
        self.button2.Click += self.reset

        self.AcceptButton = self.button1
        self.CancelButton = self.button2

        self.Controls.Add(self.textbox)
        self.Controls.Add(self.button1)
        self.Controls.Add(self.button2)


    def setupTextBox(self):
        textbox = TextBox()
        textbox.Text = "The Default Text"
        textbox.Location = Point(30, 25)
        textbox.Width = 180
        textbox.Height = 60
        textbox.Multiline = True
        textbox.ScrollBars = ScrollBars.Vertical
        textbox.AcceptsTab = True
        textbox.AcceptsReturn = True
        textbox.WordWrap = True

        self.textbox = textbox

    def reset(self, sender, event):
        self.textbox.Text = "The Default Text"


form = MultilineTextBoxForm()
Application.Run(form)

When run, it does this :

Multiline TextBox Example

and on Mono it does this :

Multiline TextBox Example

And Lots More Besides

At the start of this entry I foolishly declared that the TextBox was a nice simple widget. Well it kind of is, as you can see using it is hardly rocket science.

Despite this, it has all sorts of interesting properties and methods that could be useful in a real application. I'm too tired to show you how they all work, so I'll just list them. I will show you some code that creates a password entry box. This displays asterisks instead of the text typed, and we'll also give it a maximum length :

textbox = TextBox()
textbox.MaxLength = 20
textbox.UseSystemPasswordChar = True

This uses the properties UseSystemPasswordChar and MaxLength.

Interesting Properties

The following public properties of the TextBox class are potentially useful :

  • SelectedText - Gets or sets the selected text in the text box
  • SelectionLength - Gets or sets the number of characters selected in the text box
  • SelectionStart - Gets or sets the starting point of text selected in the text box
  • Modified - Gets or sets a value that indicates that the text box control has been modified by the user since the control was created or its contents were last set
  • TextAlign - Gets or sets how text is aligned in a TextBox control (Using a HorizontalAlignment Enumeration [3])

Interesting Methods

The TextBox also has the following methods. The combination of the properties above and these methods mean that you could implement all the basic functions of a text editor with a multi-line TextBox [4].

To use these methods you will need to read the documentation to see what arguments (if any) they take, and if they return a value. They're generally straightforward though.

  • AppendText - Appends text to the current text of a text box
  • Copy - Copies the current selection in the text box to the Clipboard
  • Cut - Moves the current selection in the text box to the Clipboard
  • DeslectAll - Specifies that the value of the SelectionLength property is zero so that no characters are selected in the control
  • Paste - Replaces the current selection in the text box with the contents of the Clipboard.
  • SelectAll - Selects all text in the text box
  • ScrollToCaret - Scrolls the contents of the control to the current caret position
  • Undo - Undoes the last edit operation in the text box

Have fun. Very Happy

[1]Multiline textboxes that allow newlines will not trigger the AcceptButton when enter is pressed.
[2]You may possibly have noticed that pressing TAB will normally move focus from one widget to the next. Smile
[3]Strangely enough the HorizontalAlignment enumeration has Center, Left and Right members.
[4]To set the cursor position set the SelectionStart property to the cursor position you want, and set SelectionLength to 0.

For buying techie books, science fiction, computer hardware or the latest gadgets: visit The Voidspace Amazon Store.

Hosted by Webfaction

Return to Top

Page rendered with rest2web the Site Builder

Last edited Fri Nov 27 18:32:35 2009.

Counter...