Visual C# | Inheritance exercise | Inheriting an abstract class to draw different textboxes

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

Software ==> Visual C#  (79 exercises)
Version ==> Any version of C#
Topic ==> Inheritance  (5 exercises)
Level ==> Harder than average
Subject ==> C# training

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Create a form with a button in (the answer form is imaginatively called Form3, but you can probably improve on this name):

A form to show inheritance

The idea is that you can click on the button to create "labels" and text boxes.  The labels will actually be textboxes with background colour, border style and enabled properties reset.


When you click on the form, we'll arrange it so that you can draw editable and non-editable textboxes on the form:

Labels and textboxes added by code

An example of what clicking on the form might show.


Here is some example code to attach to the button, which should (when you've created the requisite classes) draw the editable and non-editable textboxes as shown in the previous diagram:

// first name label

DisplayTextBox lblFirstName = new DisplayTextBox(

this, 30, 30, 150, 50);

lblFirstName.Text = "Enter first name:";



// last name label

DisplayTextBox lblLastName = new DisplayTextBox(

this, 30, 80, 150, 50);

lblLastName.Text = "Enter last name:";



// first name text box

EditableTextBox txtFirstName = new EditableTextBox(

this, 200, 30, 100, 50);



// last name text box

EditableTextBox txtLastName = new EditableTextBox(

this, 200, 80, 100, 50);


To get this to work, you will create DisplayTextBox and EditableTextBox classes which both inherit from an abstract BaseTextBox class (which in turn should inherit from System.Windows.Forms.Textbox).

If you get this all working, try creating a second button which adds the "label" and textbox in one go:

Second button

This button should do exactly the same thing, using the different code below.


Here's an example of what the code attached to this second button could look like:

// create the two "label"/textbox combinations - the answer uses

// a structure for the TextAndLabel type.

TextAndLabel tl = new TextAndLabel(this,30,30,"Enter first name");



TextAndLabel t2 = new TextAndLabel(this, 30, 80, "Enter last name");


You now understand inheritance!

You can unzip this file to see the answers to this exercise, although please remember this is for your personal use only.
This page has 0 threads Add post