Building a Basic ASP.NET Site Using IronPython
❘
235
Value = Int32.Parse(txtResult.Text)
# Reset the error message label.
lblError.Visible = False
# Obtain the new input value.
try:
Divide = Int32.Parse(txtInput.Text)
except:
# Display an error message when necessary.
lblError.Visible = True
return
# Perform the task and return the result.
Value = Value /
Divide
txtResult.Text = str(Value)
# Respond to a Clear button click.
def btnClear_Click(sender, e):
txtResult.Text = ‘0’
The code begins by importing the required assemblies. As with any IronPython application, you
can use a combination of Python modules and .NET assemblies to create your application. You also
have full access to both Python and .NET functionality in your application, so the considerable flex-
ibility that IronPython provides is still available in this environment.
Each of the event handlers must provide both the
sender
and
e
arguments as shown. You don’t
include a
self
argument in this case, as you would with other IronPython code. As you might expect,
the
sender
argument contains a reference to the control that called the event handler, while
e
contains
a list of event arguments (normally set to
None
).
The four math buttons begin by obtaining the current value of
txtResult
(the
output
TextBox
) as
an
Int32
value. Because
txtResult
is
read-only, you don’t need to worry about someone putting an
incorrect value into it. Consequently, this task doesn’t provide any error trapping code.
The next step is to obtain the new value for the math operation from
txtInput
.
In this case, you’re
relying on the user to provide the correct input value, which means that the application code could
receive anything. Someone might even try to enter a script in order to fool your application into
doing something improper. Using the
Int32.Parse()
method means that any input other than a
number triggers an exception, which your code can handle by simply not processing the input. The
try...except
structure does just that. If the
user inputs an incorrect value, the Web page displays
an error message, rather than doing anything with the input.
Now that the code has two inputs to process, it performs the required math operation. After the
math operation is complete, the code outputs the result to
txtResult.Text
.
The
btnClear_Click()
event handler is relatively simple. All it does is place a 0 in
txtResult
.Text
. The next math operation
starts with a zero value, which means that
txtResult
is cleared.
548592c11.indd 235
2/24/10 12:48:40 PM
www.finebook.ir