0

概要:

現在の ComboBox.text 値を、実行時に DataSource が割り当てられた ComboBox 内の項目のリストと照合して確認したいと考えています。テキストがリスト内の項目と一致しない場合、リスト内の最初の項目が選択されます。


これが私が最初に試したことです:

' This Load function is just here to give an example of how I bound the ComboBox '
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    Me.myComboBox.DisplayMember = "something"
    Me.myComboBox.ValueMember = "otherthing"
    Me.myComboBox.DataSource = Me.myDataTable
End Sub

' This function is copy/pasted directly out of my code '
Private Sub myComboBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles myComboBox.Validating
    If Not DirectCast(sender, ComboBox).Items.Contains(DirectCast(sender, ComboBox).Text) Then
        DirectCast(sender, ComboBox).SelectedValue = -1
    End If
End Sub

myComboBox.Itemsただし、実行時にプロパティを検査すると、実際にはSystem.Data.DataRowViewオブジェクトのコレクションであるため、上記のコードは期待どおりに機能しません。したがって、基本的には、値が実際に「System.Data.DataRowView」でない限り、常に falseと比較Stringされます...DataRowView.ToString()myComboBox.Text


ので、私は考えました

「ねえ、のすべての項目を検索してDataViewRow、要求された値がそこにあるかどうかを確認する拡張メソッドを作成しましょう!」しかし、計画どおりには進んでいません...

<Extension()>  
Private Function Contains_databound(ByVal items As ComboBox.ObjectCollection, ByVal value As Object) As Boolean
    Dim Success As Boolean = False

    For Each itm In items
        Dim item As DataRowView = Nothing

        Try
            item = DirectCast(itm, DataRowView)
        Catch ex As Exception
            Throw New Exception("Attempted to use a Contains_databound method on a non databound object", New Exception(ex.Message))
        End Try

        If Not IsNothing(item) Then
            For Each rowItem In item.Row.ItemArray
                Dim v1 As String = TryCast(rowItem, String)
                Dim v2 As String = TryCast(value, String)

                If Not IsNothing(v1) And Not IsNothing(v2) Then
                    If v1.Equals(v2) Then
                        Success = True
                    End If
                End If
            Next
        End If
    Next
    Return Success
End Function

奇妙に見えることはわかっていますが、パーツが分離されていないと、コードの整形が正しく機能し<Extension()>ません。メイン コードで拡張メソッドを使用しようとすると、拡張メソッドがメンバーではないというエラーが表示されますがComboBox.ObjectCollection、拡張メソッドでは最初のパラメーターがComboBox.ObjectCollection.

Private Sub myComboBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles myComboBox.Validating
    If DirectCast(sender, ComboBox).Items.Contains_databound(DirectCast(sender, ComboBox).Text) Then
        DirectCast(sender, ComboBox).SelectedValue = -1
    End If
End Sub

悪名高い「ポテトで脳外科手術をする方法」リクエスト...

ユーザーがデータバインドされた ComboBox に入力したテキストが DataSource の項目のリストにあることを確認するにはどうすればよいですか?

補足: C# の回答は、対応する VB.NET がある限り問題ありません。

4

2 に答える 2