選択項目を取得する

スポンサーリンク

現在選択されている項目を取得するには、SelectedItem プロパティの Content プロパティを参照します。

下記は、[選択項目を取得]ボタンがクリックされたときに、現在選択されている項目を表示する例です。

現在選択されている項目を表示する例

 

VBの例

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
    '何も選択されていない場合は処理しない
    If IsNothing(ComboBox1.SelectedItem) Then
        Return
    End If

    '選択されている項目を取得
    Dim selectedItem As String = DirectCast(ComboBox1.SelectedItem, ComboBoxItem).Content

    MessageBox.Show(selectedItem)        
End Sub

C#の例

private void button1_Click(object sender, RoutedEventArgs e)
{
    // 何も選択されていない場合は処理しない
    if (comboBox1.SelectedItem == null)
        return;

    // 選択されている項目を取得
    string selectedItem = ((ComboBoxItem)comboBox1.SelectedItem).Content.ToString();

    MessageBox.Show(selectedItem);
}
タイトルとURLをコピーしました