BindingSource.DataSource Свойство

Определение

Возвращает или задает источник данных, к которому привязан соединитель.

public:
 property System::Object ^ DataSource { System::Object ^ get(); void set(System::Object ^ value); };
public object DataSource { get; set; }
public object? DataSource { get; set; }
member this.DataSource : obj with get, set
Public Property DataSource As Object

Значение свойства

Объект Object, выступающий в качестве источника данных. Значение по умолчанию — null.

Примеры

В следующем примере кода назначается DataSource список клиентов компоненту BindingSource . Этот пример кода является частью более крупного примера, приведенного в разделе Практическое руководство. Создание уведомлений об изменениях с помощью метода BindingSource ResetItem.

void Form1_Load( Object^ /*sender*/, EventArgs^ /*e*/ )
{
   // Create and populate the list of DemoCustomer objects
   // which will supply data to the DataGridView.
   List< DemoCustomer^ >^ customerList = gcnew List< DemoCustomer^ >;
   customerList->Add( DemoCustomer::CreateNewCustomer() );
   customerList->Add( DemoCustomer::CreateNewCustomer() );
   customerList->Add( DemoCustomer::CreateNewCustomer() );
   
   // Bind the list to the BindingSource.
   this->customersBindingSource->DataSource = customerList;
   
   // Attach the BindingSource to the DataGridView.
   this->customersDataGridView->DataSource =
      this->customersBindingSource;
}
private void Form1_Load(System.Object sender, System.EventArgs e)
{
    // Create and populate the list of DemoCustomer objects
    // which will supply data to the DataGridView.
    List<DemoCustomer> customerList = new List<DemoCustomer>();
    customerList.Add(DemoCustomer.CreateNewCustomer());
    customerList.Add(DemoCustomer.CreateNewCustomer());
    customerList.Add(DemoCustomer.CreateNewCustomer());

    // Bind the list to the BindingSource.
    this.customersBindingSource.DataSource = customerList;

    // Attach the BindingSource to the DataGridView.
    this.customersDataGridView.DataSource = 
        this.customersBindingSource;
}
Private Sub Form1_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Me.Load
    ' Create and populate the list of DemoCustomer objects
    ' which will supply data to the DataGridView.
    Dim customerList As List(Of DemoCustomer) = _
    New List(Of DemoCustomer)
    customerList.Add(DemoCustomer.CreateNewCustomer())
    customerList.Add(DemoCustomer.CreateNewCustomer())
    customerList.Add(DemoCustomer.CreateNewCustomer())

    ' Bind the list to the BindingSource.
    Me.customersBindingSource.DataSource = customerList

    ' Attach the BindingSource to the DataGridView.
    Me.customersDataGridView.DataSource = Me.customersBindingSource
End Sub

Комментарии

Свойству DataSource можно задать ряд источников данных, включая типы, объекты и списки типов. Результирующий источник данных будет предоставлен в виде списка. В следующей таблице показаны некоторые распространенные источники данных и результирующая оценка списка.

Свойство DataSource Вывод списка результатов
null IBindingList Пустой объект из объектов . Добавление элемента задает для списка тип добавленного элемента.
nullс набором DataMember Не поддерживается, вызывает ArgumentException.
Тип, не относясь к списку, или объект типа "T" Пусто IBindingList с типом "T".
Экземпляр массива IBindingList содержит элементы массива.
Экземпляр IEnumerable Объект , IBindingListIEnumerable содержащий элементы .
Экземпляр списка, содержащий тип "T" IBindingList экземпляр, содержащий тип "T".

Кроме того, можно задать для других типов списков, DataSource таких как IListSource и ITypedList , и BindingSource будет обрабатывать их соответствующим образом. В этом случае тип, содержащийся в списке, должен иметь конструктор без параметров.

Если при настройке источника данных указанная ссылка содержит несколько списков или таблиц, необходимо задать DataMember для свойства строку, задающую список, к которому необходимо выполнить привязку. Задание этого свойства вызывает DataSourceChanged событие .

Примечание

Если вы вносите какие-либо изменения в DataSource значение свойства, это следует сделать в потоке пользовательского интерфейса, чтобы убедиться, что пользовательский интерфейс отражает изменения.

Свойство DataSource является свойством по умолчанию для BindingSource класса .

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

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