Поделиться через


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 Экземпляр IEnumerable Содержит IBindingList элементы.
Вывод списка экземпляров, содержащих тип "T" IBindingList экземпляр, содержащий тип "T".

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

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

Замечание

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

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

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

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