BindingSource.Find Метод

Определение

Ищет заданный элемент в источнике данных.

Перегрузки

Find(PropertyDescriptor, Object)

Выполняет поиск индекса элемента с заданным дескриптором свойства.

Find(String, Object)

Возвращает индекс элемента в списке, имеющего заданное имя свойства и значение.

Find(PropertyDescriptor, Object)

Выполняет поиск индекса элемента с заданным дескриптором свойства.

public:
 virtual int Find(System::ComponentModel::PropertyDescriptor ^ prop, System::Object ^ key);
public virtual int Find (System.ComponentModel.PropertyDescriptor prop, object key);
abstract member Find : System.ComponentModel.PropertyDescriptor * obj -> int
override this.Find : System.ComponentModel.PropertyDescriptor * obj -> int
Public Overridable Function Find (prop As PropertyDescriptor, key As Object) As Integer

Параметры

prop
PropertyDescriptor

Объект PropertyDescriptor, который требуется найти.

key
Object

Значение параметр prop для поиска соответствия.

Возвращаемое значение

Отсчитываемый от нуля индекс элемента, который имеет заданное значение дескриптора PropertyDescriptor.

Реализации

Исключения

Тип базового списка отличен от IBindingList.

Примеры

В следующем примере кода показано, как использовать метод Find. Полный пример см. в обзоре класса.

private void button1_Click(object sender, EventArgs e)
{
    if (binding1.SupportsSearching != true)
    {
        MessageBox.Show("Cannot search the list.");
    }
    else
    {
        int foundIndex = binding1.Find("Name", textBox1.Text);
        if (foundIndex > -1)
            listBox1.SelectedIndex = foundIndex;
        else
            MessageBox.Show("Font was not found.");
    }
}
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles button1.Click

        If binding1.SupportsSearching <> True Then
            MessageBox.Show("Cannot search the list.")
        Else
            Dim foundIndex As Integer = binding1.Find("Name", textBox1.Text)
            If foundIndex > -1 Then
                listBox1.SelectedIndex = foundIndex
            Else
                MessageBox.Show("Font was not found.")
            End If
        End If

    End Sub
End Class

Комментарии

Этот метод обычно используется в сложных случаях привязки данных для поиска первой строки, где значение поля, указанного prop параметром, равно значению key параметра .

Этот метод просто ссылается на запрос к методу базового списка IBindingList.Find . Например, если базовым DataSetисточником данных является , DataTableили DataView, этот метод вызывает DataView.IBindingList.Find метод . Поведение IBindingList.Find, например значение, возвращаемое, если соответствующий элемент не найден, зависит от реализации метода в базовом списке.

См. также раздел

Применяется к

Find(String, Object)

Возвращает индекс элемента в списке, имеющего заданное имя свойства и значение.

public:
 int Find(System::String ^ propertyName, System::Object ^ key);
public int Find (string propertyName, object key);
member this.Find : string * obj -> int
Public Function Find (propertyName As String, key As Object) As Integer

Параметры

propertyName
String

Имя искомого свойства.

key
Object

Значение искомого элемента с заданным свойством propertyName.

Возвращаемое значение

Отсчитываемый от нуля индекс элемента, имеющего заданное имя свойства и значение.

Исключения

Базовый список не является объектом IBindingList с реализованной функцией поиска.

Параметр propertyName не совпадает со свойством в списке.

Примеры

В следующем примере показано, как использовать Find метод с DataView. Чтобы выполнить этот пример, вставьте код в Форму Windows Form и вызовите PopulateDataViewAndFind из конструктора формы или Load метода обработки событий. Форма должна импортировать System.Xml пространства имен и System.IO .

private void PopulateDataViewAndFind()
{
    DataSet set1 = new DataSet();

    // Some xml data to populate the DataSet with.
    string musicXml =
        "<?xml version='1.0' encoding='UTF-8'?>" +
        "<music>" +
        "<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" +
        "<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" +
        "<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" +
        "<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" +
        "</music>";

    // Read the xml.
    StringReader reader = new StringReader(musicXml);
    set1.ReadXml(reader);

    // Get a DataView of the table contained in the dataset.
    DataTableCollection tables = set1.Tables;
    DataView view1 = new DataView(tables[0]);

    // Create a DataGridView control and add it to the form.
    DataGridView datagridview1 = new DataGridView();
    datagridview1.AutoGenerateColumns = true;
    this.Controls.Add(datagridview1);

    // Create a BindingSource and set its DataSource property to
    // the DataView.
    BindingSource source1 = new BindingSource();
    source1.DataSource = view1;

    // Set the data source for the DataGridView.
    datagridview1.DataSource = source1;

    // Set the Position property to the results of the Find method.
    int itemFound = source1.Find("artist", "Natalie Merchant");
    source1.Position = itemFound;
}
Private Sub PopulateDataViewAndFind() 
    Dim set1 As New DataSet()
    
    ' Some xml data to populate the DataSet with.
    Dim musicXml As String = "<?xml version='1.0' encoding='UTF-8'?>" & _
        "<music>" & _
        "<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" & _
        "<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" & _
        "<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" & _
        "<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" & _
        "</music>"
    
    ' Read the xml.
    Dim reader As New StringReader(musicXml)
    set1.ReadXml(reader)
    
    ' Get a DataView of the table contained in the dataset.
    Dim tables As DataTableCollection = set1.Tables
    Dim view1 As New DataView(tables(0))
    
    ' Create a DataGridView control and add it to the form.
    Dim datagridview1 As New DataGridView()
    datagridview1.AutoGenerateColumns = True
    Me.Controls.Add(datagridview1)
    
    ' Create a BindingSource and set its DataSource property to
    ' the DataView.
    Dim source1 As New BindingSource()
    source1.DataSource = view1
    
    ' Set the data source for the DataGridView.
    datagridview1.DataSource = source1
    
    ' Set the Position property to the results of the Find method.
    Dim itemFound As Integer = source1.Find("artist", "Natalie Merchant")
    source1.Position = itemFound

End Sub

Комментарии

Метод Find можно использовать только в том случае, если базовый список является элементом с реализованным поиском IBindingList . Этот метод просто ссылается на запрос к методу базового списка IBindingList.Find . Например, если базовым DataSetисточником данных является , DataTableили DataView, этот метод преобразуется propertyName в PropertyDescriptor и вызывает IBindingList.Find метод . Поведение Find, например значение, возвращаемое, если соответствующий элемент не найден, зависит от реализации метода в базовом списке.

Сравнение имен свойств не учитывает регистр.

Применяется к