如何:使用多个属性有选择地检索对话框信息

处理对话框返回的信息的通用方法是提供一组返回对话框数据的单个元素的属性。 这样就能有选择地从对话框中提取数据。

如果有相关的对话框数据,可考虑通过对象公开一些信息。 有关详细信息,请参见演练:使用对象整体检索对话框信息

通过属性公开对话框信息

  1. 在包含对话框的代码的类中,按需要创建任意多个属性,以公开对话框的必需信息。 提供适合于所提供的数据类型的返回值。

  2. 将代码添加到属性定义的 Get 部分。 如果要防止用户在对话框外更改对话框信息,可移除属性定义的 Set 部分。

    下面的代码演示如何通过对话框中定义的属性公开组合框 (cmbState) 的值:

    Public Property StateSelected() As String
       Get
         Return cmbState.Text
       End Get
       Set(ByVal Value As String)
    
       End Set
    End Property
    
    public string StateSelected 
    {
       get
       {
          return cmbState.Text; 
       }
    }
    
    public String StateSelected()
    {   
       return comboBox1.get_SelectedText();
    }
    

公开要提供的所有数据的属性后,则可从使用该对话框的应用程序检索数据。

从对话框的属性检索数据

  • 在显示对话框的窗体中,打开用来显示该对话框并确定其 DialogResult 的事件处理程序或方法。 添加用来收集对话框窗体属性的代码,如下列示例:

    Public Sub ShowMyDialog()
       ' Create and display an instance of the dialog box.
       Dim Dlg as New Form1()
       Dlg.ShowDialog()
    
       ' Determine the state of the DialogResult property for the form.
       If Dlg.DialogResult = DialogResult.OK Then
          ' Display the state that was selected in the dialog box's 
          ' combo box in a MessageBox.
          MessageBox.show Dlg.StateSelected
       End If
    End Sub
    
    private void ShowMyDialog() 
    {
       // Create and display an instance of the dialog box.
       Form1 dlg = new Form1();
       dlg.ShowDialog();
       // Determine the state of the DialogResult property for the form.
       if (dlg.DialogResult == DialogResult.OK) 
       {
          // Display the state that was selected in the dialog box's combo 
          // box in a MessageBox.
          MessageBox.Show (dlg.StateSelected);
       }
    }
    
    private void ShowMyDialog()
    {
       // Create and display an instance of the dialog box.
       Form1 dlg = new Form1();
       dlg.ShowDialog();
       // Determine the state of the DialogResult property for the form.
       if (dlg.get_DialogResult() == DialogResult.OK)
       {
          // Display the state that was selected in the dialog box's combo 
          // box in a MessageBox.
          MessageBox.Show(dlg.StateSelected());
       }
    }
    

请参见

任务

如何:在设计时创建对话框

如何:关闭对话框并保留用户输入

如何:检索对话框的结果

概念

对话框的用户输入

其他资源

Windows 窗体中的对话框