Exemplarische Vorgehensweise: Sammelabruf von Dialogfeldinformationen mithilfe von Objekten

Die meisten Windows Forms-Dialogfelder verfügen über Eigenschaften, die Informationen für das übergeordnete Formular verfügbar machen. Anstatt mehrere Eigenschaften zu erstellen, können Sie eine Gruppe zusammengehöriger Daten in einem einzigen Dialogfeld verfügbar machen, indem Sie ein Klassenobjekt erstellen, das alle Informationen enthält, die das übergeordnete Formular benötigt.

In der folgenden exemplarischen Vorgehensweise wird ein Dialogfeld erstellt, das eine UserInformation-Eigenschaft mit Namens- und E-Mail-Adressendaten verfügbar macht, die für das übergeordnete Formular auch dann noch verfügbar ist, wenn das Dialogfeld geschlossen wurde.

So erstellen Sie ein Dialogfeld, das seine Daten über ein Objekt zur Verfügung stellt

  1. Erstellen Sie in Visual Studio ein neues Windows Forms-Projekt mit dem Namen DialogBoxObjects. Weitere Informationen finden Sie unter Gewusst wie: Erstellen eines neuen Windows Forms-Anwendungsprojekts.

  2. Fügen Sie dem Projekt ein neues Form hinzu, und nennen Sie es InformationForm. Weitere Informationen finden Sie unter Gewusst wie: Hinzufügen von Windows Forms zu einem Projekt.

  3. Ziehen Sie aus der Toolbox ein TableLayoutPanel auf das InformationForm-Formular.

  4. Verwenden Sie das Smarttag, das neben dem TableLayoutPanel-Steuerelement als Pfeil angezeigt wird, um der Tabelle eine dritte Zeile hinzuzufügen.

  5. Ändern Sie die Größe der Zeilen mithilfe der Maus, damit alle drei Zeilen gleich sind.

  6. Ziehen Sie aus der Toolbox ein Label in jede Tabellenzelle der ersten Spalte.

  7. Legen Sie die Name-Eigenschaft der Label-Steuerelemente auf firstNameLabel, lastNameLabel und emailLabel fest.

  8. Legen Sie die Text-Eigenschaft der Steuerelemente auf First Name, Last Name und Email fest.

  9. Ziehen Sie aus der Toolbox eine TextBox in jede Zelle der zweiten Spalte.

  10. Legen Sie die Name-Eigenschaft der TextBox-Steuerelemente auf firstNameText, lastNameText und emailText fest.

  11. Ziehen Sie aus der Toolbox ein Button-Steuerelement auf das Formular.

  12. Legen Sie die Name-Eigenschaft von Button auf closeFormButton fest.

  13. Legen Sie die Text-Eigenschaft von Button auf OK fest.

  14. Fügen Sie dem Projekt eine neue Klassendatei mit dem Namen UserInformation hinzu.

  15. Fügen Sie bei einem C#-Projekt der Klassendefinition den public-Qualifizierer hinzu, damit diese Klasse außerhalb des Namespaces sichtbar ist.

  16. Fügen Sie in der UserInformation-Klasse Eigenschaftendefinitionen für die Eigenschaften FirstName, LastName und EmailAddress hinzu. Anschließend sollte der Code folgendermaßen aussehen:

    Public Class UserInformation
        Private _FirstName As String = ""
        Private _LastName As String = ""
        Private _EmailAddress As String = ""
    
        Public Property FirstName() As String
            Get
                Return _FirstName
            End Get
            Set(ByVal value As String)
                _FirstName = value
            End Set
        End Property
    
    
        Public Property LastName() As String
            Get
                Return _LastName
            End Get
            Set(ByVal value As String)
                _LastName = value
            End Set
        End Property
    
    
        Public Property EmailAddress() As String
            Get
                Return _EmailAddress
            End Get
            Set(ByVal value As String)
                _EmailAddress = value
            End Set
        End Property
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DialogBoxObjects
    {
        public class UserInformation
        {
            private string _firstName = "";
            private string _lastName = "";
            private string _emailAddress = "";
    
            public string FirstName
            {
                get
                {
                    return (_firstName);
                }
                set
                {
                    _firstName = value;
                }
            }
    
            public string LastName
            {
                get
                {
                    return (_lastName);
                }
                set
                {
                    _lastName = value;
                }
            }
    
            public string EmailAddress
            {
                get
                {
                    return (_emailAddress);
                }
                set
                {
                    _emailAddress = value;
                }
            }
        }
    }
    
    using namespace System;
    using namespace System::Collections::Generic;
    using namespace System::Text;
    
    namespace DialogBoxObjects
    {
        public ref class UserInformation
        {
        public:
            UserInformation()
            {
                firstNameValue = "";
                lastNameValue = "";
                emailAddressValue = "";
            }
        private:
            String^ firstNameValue;
        private:
            String^ lastNameValue;
        private:
            String^ emailAddressValue;
        public:
            property String^ FirstName
            {
                String^ get()
                {
                    return firstNameValue;
                }
                void set( String^ value )
                {
                    firstNameValue = value;
                }
            }
        public:
            property String^ LastName
            {
                String^ get()
                {
                    return lastNameValue;
                }
                void set( String^ value )
                {
                    lastNameValue = value;
                }
            }
        public:
            property String^ EmailAddress
            {
                String^ get()
                {
                    return emailAddressValue;
                }
                void set( String^ value )
                {
                    emailAddressValue = value;
                }
            }
        };
    }
    
  17. Klicken Sie im Projektmappen-Explorer mit der rechten Maustaste auf InformationForm, und wählen Sie Code anzeigen aus.

  18. Geben Sie auf der Code-Behind-Seite für InformationForm den folgenden Code in der InformationForm-Klasse ein, um eine UserInformation-Eigenschaft hinzuzufügen.

    Private _UI As New UserInformation()
    
    Public ReadOnly Property UserInformation() As UserInformation
        Get
            Return _UI
        End Get
    End Property
    
    UserInformation _ui = new UserInformation();
    
    public UserInformation UserInformation
    {
        get
        {
            return (_ui);
        }
    }
    
    public:
        property DialogBoxObjects::UserInformation^ UserInformation
        {
            DialogBoxObjects::UserInformation^ get()
            {
                return this->userInformation;
            }
        }
    
  19. Fügen Sie in der InformationForm-Klasse einen Validated-Ereignishandler für jedes der TextBox-Steuerelemente hinzu.

  20. Aktualisieren Sie im Ereignishandlercode die entsprechende Eigenschaft der UserInformation-Klasse immer dann, wenn sich der TextBox-Wert ändert, wie im folgenden Code gezeigt. Weitere Informationen finden Sie unter Gewusst wie: Erstellen von Ereignishandlern mithilfe des Designers.

    Private Sub FirstNameText_Validated(ByVal sender As Object, ByVal e As EventArgs) Handles FirstNameText.Validated
        Dim FirstNameTemp As String = FirstNameText.Text.Trim()
        If FirstNameText.Text.Trim().Length > 0 Then
            _UI.FirstName = FirstNameTemp
        End If
    End Sub
    
    Private Sub LastNameText_Validated(ByVal sender As Object, ByVal e As EventArgs) Handles LastNameText.Validated
        Dim LastNameTemp As String = LastNameText.Text.Trim()
        If LastNameText.Text.Trim().Length > 0 Then
            _UI.LastName = LastNameTemp
        End If
    End Sub
    
    Private Sub EmailText_Validated(ByVal sender As Object, ByVal e As EventArgs) Handles EmailText.Validated
        Dim EmailTemp As String = EmailText.Text.Trim()
        If EmailTemp.Length > 0 Then
            _UI.EmailAddress = EmailTemp
        End If
    End Sub
    
    public InformationForm()
    {
        InitializeComponent();
    
        firstNameText.Validated += new EventHandler(firstNameText_Validated);
        lastNameText.Validated += new EventHandler(lastNameText_Validated);
        emailText.Validated += new EventHandler(emailText_Validated);
    }
    
    void firstNameText_Validated(object sender, EventArgs e)
    {
        string firstNameTemp = firstNameText.Text.Trim();
        if (firstNameText.Text.Trim().Length > 0)
        {
            _ui.FirstName = firstNameTemp;
        }
    }
    
    void lastNameText_Validated(object sender, EventArgs e)
    {
        string lastNameTemp = lastNameText.Text.Trim();
        if (lastNameText.Text.Trim().Length > 0)
        {
            _ui.LastName = lastNameTemp;
        }
    }
    
    void emailText_Validated(object sender, EventArgs e)
    {
        string emailTemp = emailText.Text.Trim();
        if (emailTemp.Length > 0)
        {
            _ui.EmailAddress = emailTemp;
        }
    }
    
        private:
            void FirstNameText_Validated(Object^ sender, EventArgs^ e)
            {
                String^ firstName = firstNameText->Text->Trim();
                if (firstName->Length > 0)
                {
                    userInformation->FirstName = firstName;
                }
            }
    
        private:
            void LastNameText_Validated(Object^ sender, EventArgs^ e)
            {
                String^ lastName = lastNameText->Text->Trim();
                if (lastName->Length > 0)
                {
                    userInformation->LastName = lastName;
                }
            }
    
        private:
            void EmailText_Validated(Object^ sender, EventArgs^ e)
            {
                String^ email = emailText->Text->Trim();
                if (email->Length > 0)
                {
                    userInformation->EmailAddress = email;
                }
            }
    
        private:
            void CloseFormButton_Click(Object^ sender, EventArgs^ e)
            {
                if (userInformation->FirstName->Length == 0)
                {
                    MessageBox::Show("First name cannot be zero-length.");
                    return;
                }
                if (userInformation->LastName->Length == 0)
                {
                    MessageBox::Show("Last name cannot be zero-length.");
                    return;
                }
                if (userInformation->EmailAddress->Length == 0)
                {
                    MessageBox::Show("Email address cannot be zero-length.");
                    return;
                }
    
                this->DialogResult = ::DialogResult::OK;
                this->Hide();
            }
    
    
    
    
    #pragma region Windows Form Designer generated code
    
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
        private:
            void InitializeComponent()
            {
                this->tableLayoutPanel1 = 
                    gcnew System::Windows::Forms::TableLayoutPanel();
                this->firstNameLabel = gcnew System::Windows::Forms::Label();
                this->lastNameLabel = gcnew System::Windows::Forms::Label();
                this->emailLabel = gcnew System::Windows::Forms::Label();
                this->firstNameText = gcnew System::Windows::Forms::TextBox();
                this->lastNameText = gcnew System::Windows::Forms::TextBox();
                this->emailText = gcnew System::Windows::Forms::TextBox();
                this->closeFormButton = gcnew System::Windows::Forms::Button();
                this->tableLayoutPanel1->SuspendLayout();
                this->SuspendLayout();
                //
                // tableLayoutPanel1
                //
                this->tableLayoutPanel1->ColumnCount = 2;
                this->tableLayoutPanel1->ColumnStyles->Add(
                    gcnew System::Windows::Forms::ColumnStyle(
                    System::Windows::Forms::SizeType::Percent, 33.98533F));
                this->tableLayoutPanel1->ColumnStyles->Add(
                    gcnew System::Windows::Forms::ColumnStyle(
                    System::Windows::Forms::SizeType::Percent, 66.01467F));
                this->tableLayoutPanel1->Controls->Add(this->firstNameLabel, 0, 0);
                this->tableLayoutPanel1->Controls->Add(this->lastNameLabel, 0, 1);
                this->tableLayoutPanel1->Controls->Add(this->emailLabel, 0, 2);
                this->tableLayoutPanel1->Controls->Add(this->firstNameText, 1, 0);
                this->tableLayoutPanel1->Controls->Add(this->lastNameText, 1, 1);
                this->tableLayoutPanel1->Controls->Add(this->emailText, 1, 2);
                this->tableLayoutPanel1->Location = System::Drawing::Point(33, 30);
                this->tableLayoutPanel1->Name = "tableLayoutPanel1";
                this->tableLayoutPanel1->RowCount = 3;
                this->tableLayoutPanel1->RowStyles->Add(
                    gcnew System::Windows::Forms::RowStyle(
                    System::Windows::Forms::SizeType::Percent, 50.0F));
                this->tableLayoutPanel1->RowStyles->Add(
                    gcnew System::Windows::Forms::RowStyle(
                    System::Windows::Forms::SizeType::Percent, 50.0F));
                this->tableLayoutPanel1->RowStyles->Add(
                    gcnew System::Windows::Forms::RowStyle(
                    System::Windows::Forms::SizeType::Absolute, 41.0F));
                this->tableLayoutPanel1->Size = System::Drawing::Size(658, 116);
                this->tableLayoutPanel1->TabIndex = 0;
                //
                // firstNameLabel
                //
                this->firstNameLabel->Anchor = 
                    System::Windows::Forms::AnchorStyles::None;
                this->firstNameLabel->AutoSize = true;
                this->firstNameLabel->Location = System::Drawing::Point(82, 11);
                this->firstNameLabel->Name = "firstNameLabel";
                this->firstNameLabel->Size = System::Drawing::Size(59, 14);
                this->firstNameLabel->TabIndex = 0;
                this->firstNameLabel->Text = "First Name";
                //
                // lastNameLabel
                //
                this->lastNameLabel->Anchor = 
                    System::Windows::Forms::AnchorStyles::None;
                this->lastNameLabel->AutoSize = true;
                this->lastNameLabel->Location = System::Drawing::Point(82, 48);
                this->lastNameLabel->Name = "lastNameLabel";
                this->lastNameLabel->Size = System::Drawing::Size(59, 14);
                this->lastNameLabel->TabIndex = 1;
                this->lastNameLabel->Text = "Last Name";
                //
                // emailLabel
                //
                this->emailLabel->Anchor = 
                    System::Windows::Forms::AnchorStyles::None;
                this->emailLabel->AutoSize = true;
                this->emailLabel->Location = System::Drawing::Point(73, 88);
                this->emailLabel->Name = "emailLabel";
                this->emailLabel->Size = System::Drawing::Size(77, 14);
                this->emailLabel->TabIndex = 2;
                this->emailLabel->Text = "Email Address";
                //
                // firstNameText
                //
                this->firstNameText->Anchor = 
                    System::Windows::Forms::AnchorStyles::None;
                this->firstNameText->Location = System::Drawing::Point(339, 8);
                this->firstNameText->Name = "firstNameText";
                this->firstNameText->Size = System::Drawing::Size(203, 20);
                this->firstNameText->TabIndex = 3;
                //
                // lastNameText
                //
                this->lastNameText->Anchor = 
                    System::Windows::Forms::AnchorStyles::None;
                this->lastNameText->Location = System::Drawing::Point(339, 45);
                this->lastNameText->Name = "lastNameText";
                this->lastNameText->Size = System::Drawing::Size(202, 20);
                this->lastNameText->TabIndex = 4;
                //
                // emailText
                //
                this->emailText->Anchor = 
                    System::Windows::Forms::AnchorStyles::None;
                this->emailText->Location = System::Drawing::Point(336, 85);
                this->emailText->Name = "emailText";
                this->emailText->Size = System::Drawing::Size(208, 20);
                this->emailText->TabIndex = 5;
                //
                // closeFormButton
                //
                this->closeFormButton->Location = System::Drawing::Point(550, 211);
                this->closeFormButton->Name = "closeFormButton";
                this->closeFormButton->Size = System::Drawing::Size(141, 23);
                this->closeFormButton->TabIndex = 1;
                this->closeFormButton->Text = "OK";
                this->closeFormButton->Click += gcnew System::EventHandler(this,
                    &InformationForm::CloseFormButton_Click);
                //
                // InformationForm
                //
                this->AutoScaleDimensions = System::Drawing::SizeF(6.0F, 13.0F);
                this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
                this->ClientSize = System::Drawing::Size(744, 258);
                this->Controls->Add(this->closeFormButton);
                this->Controls->Add(this->tableLayoutPanel1);
                this->Name = "InformationForm";
                this->Text = "User Information";
                this->tableLayoutPanel1->ResumeLayout(false);
                this->tableLayoutPanel1->PerformLayout();
                this->ResumeLayout(false);
    
            }
    
    #pragma endregion
    
        public:
            InformationForm()
            {
                userInformation = gcnew DialogBoxObjects::UserInformation;
    
                components = nullptr;
                InitializeComponent();
    
                firstNameText->Validated += gcnew EventHandler
                    (this, &InformationForm::FirstNameText_Validated);
                lastNameText->Validated += gcnew EventHandler(this, 
                    &InformationForm::LastNameText_Validated);
                emailText->Validated += gcnew EventHandler(this, 
                    &InformationForm::EmailText_Validated);
            }
    
  21. Fügen Sie in der InformationForm-Klasse für das closeFormButton-Steuerelement einen Click-Ereignishandler hinzu.

  22. Überprüfen Sie im Ereignishandlercode die Eingabe, und schließen Sie das Dialogfeld, wenn die Eingabe gültig ist, wie im folgenden Code gezeigt.

    Private Sub closeFormButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        If _UI.FirstName.Length = 0 Then
            MessageBox.Show("First name cannot be zero-length.")
            Exit Sub
        End If
        If _UI.LastName.Length = 0 Then
            MessageBox.Show("Last name cannot be zero-length.")
            Exit Sub
        End If
        If _UI.EmailAddress.Length = 0 Then
            MessageBox.Show("Email address cannot be zero-length.")
            Exit Sub
        End If
    
        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub
    
    private void closeFormButton_Click(object sender, EventArgs e)
    {
        if (_ui.FirstName.Length == 0)
        {
            MessageBox.Show("First name cannot be zero-length.");
            return;
        }
        if (_ui.LastName.Length == 0)
        {
            MessageBox.Show("Last name cannot be zero-length.");
            return;
        }
        if (_ui.EmailAddress.Length == 0)
        {
            MessageBox.Show("Email address cannot be zero-length.");
            return;
        }
    
        this.DialogResult = DialogResult.OK;
        this.Hide();
    }
    
    private:
        void CloseFormButton_Click(Object^ sender, EventArgs^ e)
        {
            if (userInformation->FirstName->Length == 0)
            {
                MessageBox::Show("First name cannot be zero-length.");
                return;
            }
            if (userInformation->LastName->Length == 0)
            {
                MessageBox::Show("Last name cannot be zero-length.");
                return;
            }
            if (userInformation->EmailAddress->Length == 0)
            {
                MessageBox::Show("Email address cannot be zero-length.");
                return;
            }
    
            this->DialogResult = ::DialogResult::OK;
            this->Hide();
        }
    

So zeigen Sie das erstellte Dialogfeld an und rufen die Daten über ein Objekt ab

  1. Klicken Sie im Projektmappen-Explorer mit der rechten Maustaste auf Form1, und wählen Sie Designer anzeigen aus.

  2. Ziehen Sie aus der Toolbox ein Button-Steuerelement auf das Formular.

  3. Legen Sie die Name-Eigenschaft von Button auf showFormButton fest.

  4. Legen Sie die Text-Eigenschaft von Button auf Show Form fest.

  5. Fügen Sie einen Click-Ereignishandler für das showFormButton-Steuerelement hinzu.

  6. Rufen Sie das Dialogfeld im Ereignishandlercode auf, und zeigen Sie die Ergebnisse an, wie im folgenden Code gezeigt.

    Private Sub ShowFormButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowFormButton.Click
        Dim InfoForm As New InformationForm()
        Dim dr As DialogResult = InfoForm.ShowDialog()
        If dr = System.Windows.Forms.DialogResult.OK Then
            Dim Txt As String = "First Name: " & InfoForm.UserInformation.FirstName + ControlChars.Cr + ControlChars.Lf
            Txt &= "Last Name: " & InfoForm.UserInformation.LastName + ControlChars.Cr + ControlChars.Lf
            Txt &= "Email Address: " & InfoForm.UserInformation.EmailAddress
    
            MessageBox.Show(Txt)
        End If
    
        InfoForm.Dispose()
    End Sub
    
    private void showFormButton_Click(object sender, EventArgs e)
    {
        InformationForm iForm = new InformationForm();
        DialogResult dr = iForm.ShowDialog();
        if (dr == DialogResult.OK)
        {
            string txt = "First Name: " + iForm.UserInformation.FirstName + "\r\n";
            txt += "Last Name: " + iForm.UserInformation.LastName + "\r\n";
            txt += "Email Address: " + iForm.UserInformation.EmailAddress;
    
            MessageBox.Show(txt);
        }
    
        iForm.Dispose();
    }
    
  7. Erstellen Sie das Beispiel, und führen Sie es aus.

  8. Wenn Form1 angezeigt wird, klicken Sie auf die Schaltfläche Show Form.

  9. Wenn InformationForm angezeigt wird, geben Sie die Informationen an, und klicken Sie dann auf OK.

    Sobald Sie auf OK klicken, werden die angegebenen Informationen aus dem Formular abgerufen und in einem Meldungsfeld angezeigt. Das Formular wird geschlossen.

Siehe auch

Aufgaben

Gewusst wie: Erstellen von Dialogfeldern zur Entwurfszeit

Gewusst wie: Schließen von Dialogfeldern und Speichern von Benutzereingaben

Gewusst wie: Selektives Abrufen von Dialogfeldinformationen mithilfe mehrerer Eigenschaften

Konzepte

Benutzereingaben in Dialogfelder

Weitere Ressourcen

Dialogfelder in Windows Forms