연습: 개체를 사용하여 대화 상자 정보를 집합적으로 검색
대부분의 Windows Forms 대화 상자에는 정보를 부모 폼에 노출하는 속성이 있습니다. 여러 속성을 만드는 대신 부모 폼에서 필요한 모든 정보를 저장하는 클래스 개체를 만들어 단일 대화 상자 속성을 통해 관련 데이터 그룹을 노출할 수 있습니다.
다음 연습에서는 이름 및 전자 메일 주소 데이터가 포함된 UserInformation 속성을 노출하는 대화 상자를 만들어 대화 상자를 닫은 후에도 부모 폼에서 사용할 수 있도록 합니다.
개체를 통해 데이터를 노출하는 대화 상자를 만들려면
Visual Studio에서 DialogBoxObjects라는 새 Windows Forms 프로젝트를 만듭니다. 자세한 내용은 방법: 새 Windows Forms 응용 프로그램 프로젝트 만들기를 참조하십시오.
새 Form을 프로젝트에 추가하고 이름을 InformationForm으로 지정합니다. 자세한 내용은 방법: 프로젝트에 Windows Forms 추가를 참조하십시오.
도구 상자에서 TableLayoutPanel을 InformationForm 폼으로 끌어 옵니다.
TableLayoutPanel 컨트롤 옆에 화살표로 표시되는 스마트 태그를 사용하여 테이블에 세 번째 행을 추가합니다.
세 개의 행이 모두 같도록 마우스를 사용하여 행의 크기를 조정합니다.
도구 상자에서 Label을 첫 번째 열의 각 테이블 셀로 끌어 옵니다.
Label 컨트롤의 Name 속성을 firstNameLabel, lastNameLabel 및 emailLabel로 설정합니다.
이 컨트롤의 Text 속성을 First Name, Last Name 및 Email로 설정합니다.
도구 상자에서 TextBox를 두 번째 열의 각 셀로 끌어 옵니다.
TextBox 컨트롤의 Name 속성을 firstNameText, lastNameText 및 emailText로 설정합니다.
도구 상자에서 Button 컨트롤을 폼으로 끌어 옵니다.
프로젝트에 UserInformation이라는 새 클래스 파일을 추가합니다.
C# 프로젝트의 경우 이 클래스가 네임스페이스 외부에 표시되도록 클래스 정의에 public 한정자를 추가합니다.
UserInformation 클래스에서 FirstName, LastName 및 EmailAddress 속성에 대한 속성 정의를 추가합니다. 작업을 마치면 작성된 코드는 다음과 비슷합니다.
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; } } }; }
솔루션 탐색기에서 InformationForm을 마우스 오른쪽 단추로 클릭한 다음 코드 보기를 선택합니다.
InformationForm의 코드 숨김 페이지에서 InformationForm 클래스에 다음 코드를 입력하여 UserInformation 속성을 추가합니다.
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; } }
InformationForm 클래스에서 각 TextBox 컨트롤에 대한 Validated 이벤트 처리기를 추가합니다.
이벤트 처리기 코드에서 다음 코드와 같이 TextBox 값이 변경될 때마다 UserInformation 클래스의 해당 속성을 업데이트합니다. 자세한 내용은 방법: 디자이너를 사용하여 이벤트 처리기 만들기를 참조하십시오.
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); }
InformationForm 클래스에서 closeFormButton 컨트롤에 대한 Click 이벤트 처리기를 추가합니다.
이벤트 처리기 코드에서 다음 코드와 같이 입력의 유효성을 검사하고 입력이 유효한 경우 대화 상자를 닫습니다.
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(); }
만든 대화 상자를 표시하고 개체를 사용하여 데이터를 검색하려면
솔루션 탐색기에서 Form1을 마우스 오른쪽 단추로 클릭한 다음 디자이너 보기를 클릭합니다.
도구 상자에서 Button 컨트롤을 폼으로 끌어 옵니다.
showFormButton 컨트롤에 대한 Click 이벤트 처리기를 추가합니다.
이벤트 처리기 코드에서 다음 코드와 같이 대화 상자를 호출하고 결과를 표시합니다.
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(); }
샘플을 빌드하여 실행합니다.
Form1이 나타나면 Show Form 단추를 클릭합니다.
InformationForm이 나타나면 정보를 지정하고 확인을 클릭합니다.
확인을 클릭하면 지정한 정보가 폼에서 검색되어 메시지 상자에 표시된 다음 폼이 닫습니다.
참고 항목
작업
방법: 여러 속성을 사용하여 대화 상자 정보를 선택적으로 검색