Home

Windows Controls: The Multi-Line Text Box

 

Introduction to the Multiline Text Box

 

Description

The regular text box is meant to display one line of text. If the user enters text and presses Enter, nothing particular happens. If the user enters text and presses Tab, the focus moves to the next control in the tab sequence. You may want to create an application that goes further than the one-line limit. For example, if you have used Notepad, you would know that it shares the font characteristics of a text box but it also allows some text navigation features that require more than one line. You can create such an application based on the text box control.

ApplicationPractical Learning: Introducing Multi-Line Text Boxes

  1. Start Microsoft Visual Studion
  2. To create a new application, on the main menu, click File -> New Project
  3. In the New Project dialog box, click Windows Forms Application
  4. Set the Name to CollegeParkAutoRepair1
  5. Click OK
  6. On the main menu, click Project -> Add Class...
  7. Make sure C++ Class is selected and click Add
  8. Set the Class Name to CRepairOrder
  9. Click Finish
  10. Complete the header file as follows:
    #pragma once
    using namespace System;
    using namespace System::Collections::Generic;
    
    [Serializable]
    public ref class CPart
    {
    public:
        String ^ PartName;
        double   UnitPrice;
        int      Quantity;
        double   SubTotal;
    };
    
    [Serializable]
    public ref class CJobPerformed
    {
    public:
        String ^ Job;
        double   Cost;
    };
    
    [Serializable]
    public ref class CRepairOrder
    {
    public:
        CRepairOrder(void);
    	
        String ^ CustomerName;
        String ^ Address;
        String ^ City;
        String ^ State;
        String ^ ZIPCode;
        String ^ Make;
        String ^ Model;
        int Year;
        String ^ ProblemDescription;
        List<CPart ^> ^ Parts;
        List<CJobPerformed ^> ^ Jobs;
        double TotalParts;
        double TotalLabor;
        double TaxRate;
        double TaxAmount;
        double RepairTotal;
        String ^ Recommendations;
    };

Creating a Multi-Line Text Box

The TextBox control is equipped with one particular property that, when considered, changes the control tremendously. This property is called Multiline. Multiline is a Boolean property whose default value is false. If it is set to a true value, it allows the control to display multiple lines of text, unlike the normal text box that can display only one line. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class CExercise : Form
{
private:
    TextBox ^ txtNotice;

public:
	CExercise()
    {
        InitializeComponent();
    }
	
private:
    void InitializeComponent()
    {
        txtNotice = gcnew TextBox;
        txtNotice->Location = Point(12, 12);
	txtNotice->Size = System::Drawing::Size(500, 200);

	txtNotice->Multiline = true;

        Controls->Add(txtNotice);
	Text = "Notice";
	Size = System::Drawing::Size(532, 252);
    }
};

[STAThread]
int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise);

    return 0;
}

Multi-Line Text Box

ApplicationPractical Learning: Creating a Multi-Line Text Box

  1. Design the form as follows:
     
    College Park Auto Repair
    Control Name Text Other Properties
    GroupBox GroupBox   Order Identification  
    Label Label   Customer Name:  
    TextBox TextBox txtCustomerName    
    Label Label   Address  
    TextBox TextBox txtAddress    
    Label Label   City:  
    TextBox TextBox txtCity    
    Label Label   State:  
    TextBox TextBox txtState    
    Label Label   ZIP Code:  
    TextBox TextBox txtZIPCode   TextAlign: Right
    Label Label   Make / Model:  
    TextBox TextBox txtMake    
    TextBox TextBox txtModel    
    Label Label   Year:  
    TextBox TextBox txtCarYear   TextAlign: Right
    Label Label   Problem Description:  
    TextBox TextBox txtProblem   Mutltiline: True
    GroupBox GroupBox   Parts Used  
    DataGridView DataGridView dgvPartsUsed    
    Columns  
    Header Text Name Width
    Part Name/Description colPartName 215
    Unit Price colUnitPrice 80
    Qty colQuantity 30
    Sub-Total colSubTotal 60
    GroupBox GroupBox   Jobs Performed  
    DataGridView DataGridView dgvJobsPerformed    
    Columns  
    Header Text Name Width
    Job Performed colJobPerformed 320
    Cost colCost 60
    GroupBox GroupBox   Repair Summary  
    Label Label   Total Parts:  
    TextBox TextBox txtTotalParts 0.00 TextAlign: Right
    Label Label   Tax Rate:  
    TextBox TextBox txtTaxRate 5.75 TextAlign: Right
    Label Label   %  
    Label Label   Total Labor:  
    TextBox TextBox txtTotalLabor 0.00 TextAlign: Right
    Label Label   Tax Amount:  
    TextBox TextBox txtTaxAmount 0.00 TextAlign: Right
    Label Label   RepairTotal:  
    TextBox TextBox txtRepairTotal 0.00 TextAlign: Right
    Label Label   Recommendations  
    TextBox TextBox txtRecommendations   Multiline: True
    OpenFileDialog OpenFileDialog dlgOpen   DefaultExt: rpr
    Filter: Repair Orders (*.rpr)|*.rpr|All Files|
    Title: Open Existing Repair Order
    SaveFileDialog SaveFileDialog dlgSave  

    DefaultExt: rpr
    Filter: Repair Orders (*.rpr)|*.rpr|All Files|
    Title: Save Current Repair Order

    PrintDocument PrintDocument docPrint  

     

    PrintDialog PrintDialog dlgPrint   

    Document: docPrint

    PageSetupDialog dlgPageSetup   Document: docPrint
    PrintPreviewDialog Print Preview Dialog dlgPrintPreview   Document: docPrint
  2. On the form, click the data grid view in the Parts Used group
  3. In the properties window, click Events and double-click CellLeave
  4. Implement the event as follows:
    void CalculateTotal()
    {
        double taxRate = 0.00, taxAmount = 0.00;
        double totalParts = 0.00, totalLabor = 0.00, totalPartsAndLabor, repairTotal;
    
        for each( DataGridViewRow ^ record in dgvPartsUsed->Rows)
        {
            try
            {
                totalParts += double::Parse(record->Cells[3]->EditedFormattedValue->ToString());
                txtTotalParts->Text = totalParts.ToString("F");
            }
            catch(FormatException ^)
            {
            }
        }
    
        for each(DataGridViewRow ^ record in dgvJobsPerformed->Rows)
        {
            try
            {
                totalLabor += double::Parse(record->Cells[1]->EditedFormattedValue->ToString());
                txtTotalLabor->Text = totalLabor.ToString("F");
            }
            catch(FormatException ^)
            {
            }
        }
    
        try
        {
            taxRate = double::Parse(txtTaxRate->Text);
        }
        catch(FormatException ^)
        {
            MessageBox::Show("Invalid Tax Rate",
                        "College Park Auto Repair",
                        MessageBoxButtons::YesNoCancel,
                        MessageBoxIcon::Question);
            txtTaxRate->Text = "5.75";
            txtTaxRate->Focus();
        }
    
        totalPartsAndLabor = totalParts + totalLabor;
    
        taxAmount = totalPartsAndLabor * taxRate / 100;
        repairTotal = totalPartsAndLabor + taxAmount;
    
        txtTotalParts->Text = totalParts.ToString("F");
        txtTotalLabor->Text = totalLabor.ToString("F");
        txtTaxAmount->Text = taxAmount.ToString("F");
        txtRepairTotal->Text = repairTotal.ToString("F");
    }
    System::Void dgvPartsUsed_CellLeave(System::Object^  sender,
    	                            System::Windows::Forms::DataGridViewCellEventArgs^  e)
    {
    	if( e->ColumnIndex == 2)
        {
            double unitPrice = 0.00;
            int quantity = 0;
            double subTotal = 0.00;
            
            DataGridViewCell ^ dgvcUnitPrice = dgvPartsUsed->Rows[e->RowIndex]->Cells[1];
            DataGridViewCell ^ dgvcQuantity = dgvPartsUsed->Rows[e->RowIndex]->Cells[e->ColumnIndex];
    
            unitPrice = double::Parse(dgvcUnitPrice->EditedFormattedValue->ToString());
            quantity = int::Parse(dgvcQuantity->EditedFormattedValue->ToString());
            subTotal = unitPrice * quantity;
            dgvPartsUsed->Rows[e->RowIndex]->Cells[3]->Value = subTotal.ToString("F");
    
            CalculateTotal();
        }
    }
  5. Return to the form
  6. Click the Jobs Performed data grid view
  7. In the Events section of the properties window, double-click CellLeave
  8. Implement the event as follows:
    System::Void dgvJobsPerformed_CellLeave(System::Object^  sender,
    	System::Windows::Forms::DataGridViewCellEventArgs^  e)
    {
    	CalculateTotal();
    }
  9. Return to the form
  10. On the form, click File and double-click New Repair Order
  11. Implement its Click event as follows:
    System::Void newToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e)
    {
        txtCustomerName->Text = "";
        txtAddress->Text = "";
        txtCity->Text = "";
        txtState->Text = "";
        txtZIPCode->Text = "";
        txtMake->Text = "";
        txtModel->Text = "";
        txtYear->Text = "";
        txtProblemDescription->Text = "";
    
        dgvPartsUsed->Rows->Clear();
        dgvJobsPerformed->Rows->Clear();
    
        txtTotalParts->Text = "0.00";
        txtTotalLabor->Text = "0.00";
        txtTaxRate->Text = "5.75";
        txtTaxAmount->Text = "0.00";
        txtRepairTotal->Text = "0.00";
    
        txtRecommendations->Text = "";
        txtCustomerName->Focus();
    }
  12. In the top section of the file, type the following:
    #include "RepairOrder.h"
    
    namespace CollegeParkAutoRepair1
    {
        using namespace System;
        using namespace System::ComponentModel;
        using namespace System::Collections;
        using namespace System::Windows::Forms;
        using namespace System::Data;
        using namespace System::Drawing;
        using namespace System::IO;
        using namespace System::Runtime::Serialization::Formatters::Binary;
  13. Return to the form
  14. On the form, click File and double-click Save As...
  15. Implement its Click event as follows:
    System::Void saveAsToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	// Just in case, calculate the order now
        CalculateTotal();
    
        // Check the folder that will contain the repair order->
        // If it exists, don't create it.
        // If it doesn't exist, then create it
        String ^ strDirectory = "C:\\College Park Auto Repair";
        DirectoryInfo ^ dirInfo = Directory::CreateDirectory(strDirectory);
    
        // Prepare to create a repair order
        CRepairOrder ^ order = gcnew CRepairOrder;
    
    
        // Display the Save As dialog box.
        // Select the above directory
        dlgSave->InitialDirectory = strDirectory;
        // Check if the user clicked OK
        if( dlgSave->ShowDialog() == System::Windows::Forms::DialogResult::OK)
        {
            // If the user clicked OK, create a repair order
            order->CustomerName = txtCustomerName->Text;
            order->Address = txtAddress->Text;
            order->City = txtCity->Text;
            order->State = txtState->Text;
            order->ZIPCode = txtZIPCode->Text;
            order->Make = txtMake->Text;
            order->Model = txtModel->Text;
            order->Year = int::Parse(txtYear->Text);
            order->ProblemDescription = txtProblemDescription->Text;
    
            // Check whether the Parts Used data grid view contains some records.
            // If it does, save them
            if( dgvPartsUsed->Rows->Count > 1)
            {
                List<CPart ^> ^parts = gcnew List<CPart ^>;
    
                for (int row = 0; row < dgvPartsUsed->Rows->Count - 1; row++ )
                {
                    CPart ^ prt = gcnew CPart;
                    prt->PartName = dgvPartsUsed->Rows[row]->Cells[0]->EditedFormattedValue->ToString();
                    prt->UnitPrice = double::Parse(dgvPartsUsed->Rows[row]->Cells[1]->EditedFormattedValue->ToString());
                    prt->Quantity = int::Parse(dgvPartsUsed->Rows[row]->Cells[2]->EditedFormattedValue->ToString());
                    prt->SubTotal = double::Parse(dgvPartsUsed->Rows[row]->Cells[3]->EditedFormattedValue->ToString());
                    parts->Add(prt);
                }
                order->Parts = parts;
            }
            else // If the data grid view is empty, flag its value as null
                order->Parts = nullptr;
    
            if( dgvJobsPerformed->Rows->Count > 1)
            {
                List<CJobPerformed ^> ^ work = gcnew List<CJobPerformed ^>;
    
                for (int row = 0; row < dgvJobsPerformed->Rows->Count - 1; row++)
                {
                    CJobPerformed ^ done = gcnew CJobPerformed;
                    done->Job = dgvJobsPerformed->Rows[row]->Cells[0]->EditedFormattedValue->ToString();
                    done->Cost = double::Parse(dgvJobsPerformed->Rows[row]->Cells[1]->EditedFormattedValue->ToString());
                    work->Add(done);
                }
    
                order->Jobs = work;
            }
    
            order->TotalParts = double::Parse(txtTotalParts->Text);
            order->TotalLabor = double::Parse(txtTotalLabor->Text);
            order->TaxRate = double::Parse(txtTaxRate->Text);
            order->TaxAmount = double::Parse(txtTaxAmount->Text);
            order->RepairTotal = double::Parse(txtRepairTotal->Text);
            order->Recommendations = txtRecommendations->Text;
    
            FileStream ^ stmRepair = gcnew FileStream(dlgSave->FileName,
                                                       FileMode::Create);
            BinaryFormatter ^ bfmRepair = gcnew BinaryFormatter;
            bfmRepair->Serialize(stmRepair, order);
    
            stmRepair->Close();
            newToolStripMenuItem_Click(sender, e);
        }
    }
  16. Return to the form
  17. On the form, click File and double-click Open...
  18. Implement the event as follows:
    System::Void openToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e)
    {
        dlgOpen->InitialDirectory = "C:\\College Park Auto Repair";
    
        if( dlgOpen->ShowDialog() == System::Windows::Forms::DialogResult::OK)
        {
            FileStream ^ stmRepair = gcnew FileStream(dlgOpen->FileName,
                                                      FileMode::Open);
            BinaryFormatter ^ bnrRepair = gcnew BinaryFormatter;
            CRepairOrder ^ order = reinterpret_cast<CRepairOrder ^>(bnrRepair->Deserialize(stmRepair));
    
            txtCustomerName->Text = order->CustomerName;
            txtAddress->Text = order->Address;
            txtCity->Text = order->City;
            txtState->Text = order->State;
            txtZIPCode->Text = order->ZIPCode;
            txtMake->Text = order->Make;
            txtModel->Text = order->Model;
            txtYear->Text = order->Year.ToString();
            txtProblemDescription->Text = order->ProblemDescription;
    
            int i = 0;
            for each(CPart ^ prt in order->Parts)
            {
                dgvPartsUsed->Rows->Add();
    
                dgvPartsUsed->Rows[i]->Cells[0]->Value = prt->PartName;
                dgvPartsUsed->Rows[i]->Cells[1]->Value = prt->UnitPrice.ToString("F");
                dgvPartsUsed->Rows[i]->Cells[2]->Value = prt->Quantity.ToString();
                dgvPartsUsed->Rows[i]->Cells[3]->Value = prt->SubTotal.ToString("F");
                i++;
            }
    
            i = 0;
            for each(CJobPerformed ^ jp in order->Jobs)
            {
                dgvJobsPerformed->Rows->Add();
    
                dgvJobsPerformed->Rows[i]->Cells[0]->Value = jp->Job;
                dgvJobsPerformed->Rows[i]->Cells[1]->Value = jp->Cost;
                i++;
            }
    
            txtTotalParts->Text = order->TotalParts.ToString("F");
            txtTotalLabor->Text = order->TotalLabor.ToString("F");
            txtTaxRate->Text = order->TaxRate.ToString("F");
            txtTaxAmount->Text = order->TaxAmount.ToString("F");
            txtRepairTotal->Text = order->RepairTotal.ToString("F");
            txtRecommendations->Text = order->Recommendations;
    
            stmRepair->Close();
        }
    }
  19. To execute the application, press F5
  20. Create a repair order-> Here is an example:
     
    College Park Auto Repair
  21. On the main menu of the form, click File -> Save As...
  22. Set the name to 100001 and click Save
  23. Create another order, calculate it and save it
  24. Try opening a previously saved order
  25. Close the form and return to your programming environment
 
 
 

Characteristics of a Multi-Line Text Box

 

Introduction

The multi-line text box shares all of the properties of the single-line text box. These include the read-only attribute, the character casing, and the password options. Although these properties are valid, some of them may not be suitable for a multi-line text box, such as applying a password character to hide the text, trying to auto-complete a string while the user is typing it, etc. This is why, in most cases, we will tend to consider the single-line and the multiple line objects are separate controls.

The Lines of Text

By default, when you add a new text box to your form, it appears empty. When the application comes up, the user mostly reads and/or enters text in the multi-line text box when interacting with the control. At design time, you can set the text that would display when the multi-line text box comes up. To support multiple lines of text, the TextBox class is equipped with a property named Lines:

public:
    property array<String^>^ Lines
    {
        array<String^>^ get ();
        void set (array<String^>^ value);
    };

As you can see, the Lines proeprty is an array, which is also serializable. During design, to manually create the lines of text, in the Properties window, click the Lines field, then click its ellipsis button. That would open the String Collection Editor. Type the desired text and click OK. On the other hand, after the user has entered some text or a few lines of text in the control, it holds these lines. The lines of text of a text box are stored in an array represented by a property named Lines. This means that, at run time, you can create an array of lines of text and assign it to the text box. Here is an example:

void InitializeComponent()
{
    txtNotice = gcnew TextBox;
    txtNotice->Location = Point(12, 12);
    txtNotice->Size = System::Drawing::Size(500, 200);

    txtNotice->Multiline = true;

    array<String^>^ lines = { "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
	                      "Curabitur luctus tellus non nulla fringilla non "
			      "condimentum libero luctus. Aliquam ante neque, porttitor "
			      "at convallis et, iaculis vitae massa.",
			      "Nunc massa turpis, dignissim in congue nec, sodales nec "
			      "elit. Integer eleifend tellus eget neque vulputate "
			      "fermentum. Quisque tellus est, dictum et laoreet at, "
			      "dignissim id erat. Nam libero dolor, dapibus et ultrices "
			      "non, tempor sed velit. Cras mollis imperdiet neque.",
			      "Curabitur orci ligula, placerat hendrerit volutpat vel, "
			      "elementum non quam. Vestibulum ante ipsum primis in "
			      "faucibus orci luctus et ultrices posuere cubilia Curae; "
			      "Cras luctus nunc ac sem mollis accumsan adipiscing augue euismod." };

    txtNotice->Lines = lines;

    Controls->Add(txtNotice);
    Text = "Notice";
    Size = System::Drawing::Size(532, 252);
}

Multi-Line Text Box

Or, to get the lines of text of the control, you can retrieve the value of the Lines property.

The Modified Attribute

When a multi-line text box opens, the compiler registers the content of the control. If the user has the ability to change the text in the control and if the user changes it, the compiler flags the control as Modified. This allows you to take actions. You can acknowledge this by programmatically setting the Modified property to true. If another control or some other action alters the contents of the multi-line text box, you can make sure that this property reflects the change. You can change this programmatically as follows:

void InitializeComponent()
{
    txtNotice = gcnew TextBox;
    txtNotice->Location = Point(12, 12);
    txtNotice->Size = System::Drawing::Size(500, 200);
    txtNotice->Multiline = true;
    array<String^>^ lines = { "" };
    txtNotice->Lines = lines;

    txtNotice->Modified = true;

    Controls->Add(txtNotice);
    Text = "Notice";
    Size = System::Drawing::Size(532, 252);
}

The Maximum Length of Text

The multi-line text box allows the user to enter up to 32767 characters. If you want to limit the maximum number of characters that the user can enter to a value lower than this, you can use the MaxLength property at design time. You can also change this programmatically. Here is an example:

void InitializeComponent()
{
    txtNotice = gcnew TextBox;
    txtNotice->Location = Point(12, 12);
    txtNotice->Size = System::Drawing::Size(500, 200);
    txtNotice->Multiline = true;

    textBox1->MaxLength = 1020;

    Controls->Add(txtNotice);
    Text = "Notice";
    Size = System::Drawing::Size(532, 252);
}

Using the Enter Key

If the control will be used to enter text, the user can press Enter at the end of a line to move to the next line. This ability is controlled by the Boolean AcceptsReturn property:

public:
    property bool AcceptsReturn
    {
        bool get();
        void set(bool value);
    }

By default, this property is set to False because this control is primarily created from a normal single-line TextBox control that has no formal action to take when the user presses Enter. If you are creating a multi-line text box and you expect your users to perform some type of text editing, you certainly should allow them to press Enter to move to the next line. Therefore, in most cases, when creating a multi-line text box, you should set its AcceptsReturn property to True. To set it programmatically, assign the desired value to the AcceptstReturn property. Here is an example:

void InitializeComponent()
{
    txtNotice = gcnew TextBox;
    txtNotice->Location = Point(12, 12);
    txtNotice->Size = System::Drawing::Size(500, 200);
    txtNotice->Multiline = true;
    txtNotice->MaxLength = 1020;
    
    txtNotice->AcceptsReturn = true;
        
    Controls->Add(txtNotice);
    Text = "Notice";
    Size = System::Drawing::Size(532, 252);
}

Using the Tab Key

The user is accustomed to pressing Tab to insert tab characters in the text. By default, when the user presses Tab when interacting with your application, the focus moves from one control to the next, following the TabIndex values of the form. Even when using a multi-line text box to perform text editing, if the user presses Tab, the focus would switch to another control or to the form. If you want a multi-line text box to receive focus when the user presses the Tab key, set the AcceptTab property from False (the default), to True.

When entering text in a multi-line text box control, the characters start on the left side of the multi-line text box and are subsequently added on the right side. The ability to align text is controlled by the TextAlign property. For a multi-line text box control, the alignment is configured using the HorizontalAlignment enumerator.

Wrapping Text

As the user enters text in a multi-line text box box, the compiler considers that a paragraph starts from the user typing a character until he or she presses Enter. Therefore, a paragraph could be an empty space, a character, a word, a line of text, a whole page or an entire book. Depending on the width of the multi-line text box control, the text is incrementally added to the right side of each previous character. If the caret gets to the right border of the control, the text automatically continues to the next line, although it is still considered as one paragraph. To start a new paragraph, the user has to press Enter. The ability for the text to continue on the next line when the caret encounters the right border of the multi-line text box is controlled by the WordWrap property:

public:
    property bool WordWrap
    {
        bool get();
        void set(bool value);
    }

Its default Boolean value is set to true. If you do not want text to wrap to the subsequent line, set the WordWrap property to false. You can also set it programmatically as follows:

void InitializeComponent()
{
    txtNotice = gcnew TextBox;
    txtNotice->Location = Point(12, 12);
    txtNotice->Size = System::Drawing::Size(500, 200);
    txtNotice->Multiline = true;
    txtNotice->MaxLength = 1020;
    txtNotice->AcceptsReturn = true;
    
    txtNotice->WordWrap = false;
        
    Controls->Add(txtNotice);
    Text = "Notice";
    Size = System::Drawing::Size(532, 252);
}

Using Scroll Bars

When a text box has been configured to hold multiple lines and once its text becomes too long, part of the content could become hidden. To show the hidden part, the control should be equipped with scrollbars so the user can navigate up and down, left and right. To support the display of scrollbars, the TextBox class is equipped with the ScrollBars property:

public:
    property ScrollBars ScrollBars
    {
        ScrollBars get();
        void set(ScrollBars value);
    }

You can specify the option of this property at either the design time or the run time or both.

The TextBox::ScrollBars property is based on the ScrollBars enumeration that has four members:

  • None: This is the default value and its means that the text box would not display any scrollbar
  • Vertical: This option specifies that the text box should display a vertical scroll bar when its content becomes too long
  • Horizontal: This is valid only if the WordWrap property is set to false. In this case, the text box would display a horizontal scroll bar
  • Both: This allows displaying both the vertical and the horizontal scrollbars

Here is an example:

void InitializeComponent()
{
    txtNotice = gcnew TextBox;
    txtNotice->Location = Point(12, 12);
    txtNotice->Size = System::Drawing::Size(500, 200);

    txtNotice->Multiline = true;
    txtNotice->AcceptsReturn = true;
    txtNotice->WordWrap = true;
    
    txtNotice->ScrollBars = ScrollBars::Vertical;

    array<String^>^ lines = { "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
	                      "Curabitur luctus tellus non nulla fringilla non "
			      "condimentum libero luctus. Aliquam ante neque, porttitor "
			      "at convallis et, iaculis vitae massa.",
			      "Nunc massa turpis, dignissim in congue nec, sodales nec "
			      "elit. Integer eleifend tellus eget neque vulputate "
			      "fermentum. Quisque tellus est, dictum et laoreet at, "
			      "dignissim id erat. Nam libero dolor, dapibus et ultrices "
			      "non, tempor sed velit. Cras mollis imperdiet neque.",
			      "Curabitur orci ligula, placerat hendrerit volutpat vel, "
			      "elementum non quam. Vestibulum ante ipsum primis in "
			      "faucibus orci luctus et ultrices posuere cubilia Curae; "
			      "Cras luctus nunc ac sem mollis accumsan adipiscing augue euismod." };

	txtNotice->Lines = lines;

        Controls->Add(txtNotice);
	txtNotice->Modified = true;
	Text = "Notice";
	Size = System::Drawing::Size(532, 252);
}

Multi-Line Text Box

ApplicationPractical Learning: Adding Scroll Bars

  1. On the form, click one of the multiline text boxes
  2. In the Properties window, click ScrollBars, then click the arrow of its field, and select Vertical
  3. On the form, click the other multiline text boxes
  4. In the Properties window, double-click ScrollBars until it displays Vertical

Member Functions to Manage a Multi-Line Text Box

The multi-line text box control is based on the TextBox class. To dynamically create a multi-line text box, declare a TextBox variable and use its default constructor to initialize it. The other operations the user can perform on a multi-line text box can be controlled by member functions such as Undo(), Cut(), Copy(), Paste(), Clear() or SelectAll() that we reviewed for the text box control and they function the same.

Here are examples: 

System::Void mnuEditUndo_Click(Object ^ sender, EventArgs ^ e)
{
    txtNotice->Undo();
}
System::Void mnuEditCut_Click(Object ^ sender, EventArgs ^ e)
{
    txtNotice->Cut();
}
System::Void mnuEditCopy_Click(Object ^ sender, EventArgs ^ e)
{
    txtNotice->Copy();
}
System::Void mnuEditPaste_Click(Object ^ sender, EventArgs ^ e)
{
     txtNotice->Paste();
}
 
 
   
 

Previous Copyright © 2011 FunctionX, Inc. Home