DataGridViewComboBoxCell.DataSource Propriété

Définition

Obtient ou définit la source de données dont les données contiennent les sélections possibles affichées dans la liste déroulante.Gets or sets the data source whose data contains the possible selections shown in the drop-down list.

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

Valeur de propriété

IList ou IListSource qui contient une collection de valeurs utilisées pour fournir des données à la liste déroulante.An IList or IListSource that contains a collection of values used to supply data to the drop-down list. La valeur par défaut est null.The default value is null.

Exceptions

La valeur spécifiée lors de la définition de cette propriété n'est pas null et son type n'est ni IList, ni IListSource.The specified value when setting this property is not null and is not of type IList nor IListSource.

Exemples

L’exemple de code suivant illustre l’utilisation de la propriété DataGridViewComboBoxColumn.DataSource, qui est similaire à cette propriété.The following code example demonstrates the use of the DataGridViewComboBoxColumn.DataSource property, which is similar to this property. Cet exemple fait partie d’un exemple plus complet disponible dans la rubrique vue d’ensemble de la classe DataGridViewComboBoxColumn.This example is part of a larger example available in the DataGridViewComboBoxColumn class overview topic.

private:
    DataGridViewComboBoxColumn^ CreateComboBoxColumn()
    {
        DataGridViewComboBoxColumn^ column =
            gcnew DataGridViewComboBoxColumn();
        {
            column->DataPropertyName = ColumnName::TitleOfCourtesy.ToString();
            column->HeaderText = ColumnName::TitleOfCourtesy.ToString();
            column->DropDownWidth = 160;
            column->Width = 90;
            column->MaxDropDownItems = 3;
            column->FlatStyle = FlatStyle::Flat;
        }
        return column;
    }

private:
    void SetAlternateChoicesUsingDataSource(DataGridViewComboBoxColumn^ comboboxColumn)
    {
        {
            comboboxColumn->DataSource = RetrieveAlternativeTitles();
            comboboxColumn->ValueMember = ColumnName::TitleOfCourtesy.ToString();
            comboboxColumn->DisplayMember = comboboxColumn->ValueMember;
        }
    }

private:
    DataTable^ RetrieveAlternativeTitles()
    {
        return Populate("SELECT distinct TitleOfCourtesy FROM Employees");
    }

    String^ connectionString;

private:
    DataTable^ Populate(String^ sqlCommand)
    {
        SqlConnection^ northwindConnection = gcnew SqlConnection(connectionString);
        northwindConnection->Open();

        SqlCommand^ command = gcnew SqlCommand(sqlCommand, northwindConnection);
        SqlDataAdapter^ adapter = gcnew SqlDataAdapter();
        adapter->SelectCommand = command;

        DataTable^ table = gcnew DataTable();
        adapter->Fill(table);

        return table;
    }

    // Using an enum provides some abstraction between column index
    // and column name along with compile time checking, and gives
    // a handy place to store the column names.
    enum class ColumnName
    {
        EmployeeID,
        LastName,
        FirstName,
        Title,
        TitleOfCourtesy,
        BirthDate,
        HireDate,
        Address,
        City,
        Region,
        PostalCode,
        Country,
        HomePhone,
        Extension,
        Photo,
        Notes,
        ReportsTo,
        PhotoPath,
        OutOfOffice
    };
private DataGridViewComboBoxColumn CreateComboBoxColumn()
{
    DataGridViewComboBoxColumn column =
        new DataGridViewComboBoxColumn();
    {
        column.DataPropertyName = ColumnName.TitleOfCourtesy.ToString();
        column.HeaderText = ColumnName.TitleOfCourtesy.ToString();
        column.DropDownWidth = 160;
        column.Width = 90;
        column.MaxDropDownItems = 3;
        column.FlatStyle = FlatStyle.Flat;
    }
    return column;
}

private void SetAlternateChoicesUsingDataSource(DataGridViewComboBoxColumn comboboxColumn)
{
    {
        comboboxColumn.DataSource = RetrieveAlternativeTitles();
        comboboxColumn.ValueMember = ColumnName.TitleOfCourtesy.ToString();
        comboboxColumn.DisplayMember = comboboxColumn.ValueMember;
    }
}

private DataTable RetrieveAlternativeTitles()
{
    return Populate("SELECT distinct TitleOfCourtesy FROM Employees");
}

string connectionString =
    "Integrated Security=SSPI;Persist Security Info=False;" +
    "Initial Catalog=Northwind;Data Source=localhost";

private DataTable Populate(string sqlCommand)
{
    SqlConnection northwindConnection = new SqlConnection(connectionString);
    northwindConnection.Open();

    SqlCommand command = new SqlCommand(sqlCommand, northwindConnection);
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = command;

    DataTable table = new DataTable();
    table.Locale = System.Globalization.CultureInfo.InvariantCulture;
    adapter.Fill(table);

    return table;
}

// Using an enum provides some abstraction between column index
// and column name along with compile time checking, and gives
// a handy place to store the column names.
enum ColumnName
{
    EmployeeId,
    LastName,
    FirstName,
    Title,
    TitleOfCourtesy,
    BirthDate,
    HireDate,
    Address,
    City,
    Region,
    PostalCode,
    Country,
    HomePhone,
    Extension,
    Photo,
    Notes,
    ReportsTo,
    PhotoPath,
    OutOfOffice
};
Private Function CreateComboBoxColumn() _
    As DataGridViewComboBoxColumn
    Dim column As New DataGridViewComboBoxColumn()

    With column
        .DataPropertyName = ColumnName.TitleOfCourtesy.ToString()
        .HeaderText = ColumnName.TitleOfCourtesy.ToString()
        .DropDownWidth = 160
        .Width = 90
        .MaxDropDownItems = 3
        .FlatStyle = FlatStyle.Flat
    End With
    Return column
End Function

Private Sub SetAlternateChoicesUsingDataSource( _
    ByVal comboboxColumn As DataGridViewComboBoxColumn)
    With comboboxColumn
        .DataSource = RetrieveAlternativeTitles()
        .ValueMember = ColumnName.TitleOfCourtesy.ToString()
        .DisplayMember = .ValueMember
    End With
End Sub

Private Function RetrieveAlternativeTitles() As DataTable
    Return Populate( _
        "SELECT distinct TitleOfCourtesy FROM Employees")
End Function

Private connectionString As String = _
        "Integrated Security=SSPI;Persist Security Info=False;" _
        & "Initial Catalog=Northwind;Data Source=localhost"

Private Function Populate(ByVal sqlCommand As String) As DataTable
    Dim northwindConnection As New SqlConnection(connectionString)
    northwindConnection.Open()

    Dim command As New SqlCommand(sqlCommand, _
        northwindConnection)
    Dim adapter As New SqlDataAdapter()
    adapter.SelectCommand = command
    Dim table As New DataTable()
    table.Locale = System.Globalization.CultureInfo.InvariantCulture
    adapter.Fill(table)

    Return table
End Function

' Using an enum provides some abstraction between column index
' and column name along with compile time checking, and gives
' a handy place to store the column names.
Enum ColumnName
    EmployeeId
    LastName
    FirstName
    Title
    TitleOfCourtesy
    BirthDate
    HireDate
    Address
    City
    Region
    PostalCode
    Country
    HomePhone
    Extension
    Photo
    Notes
    ReportsTo
    PhotoPath
    OutOfOffice
End Enum

Remarques

En général, cette propriété est définie pour une colonne entière de cellules à l’aide de la propriété DataGridViewComboBoxColumn.DataSource.Typically this property is set for an entire column of cells through the DataGridViewComboBoxColumn.DataSource property.

Si possible, définissez DataSource sur une source contenant uniquement les sélections possibles, par exemple une colonne de sélections.If possible, set DataSource to a source containing only the possible selections, like a column of selections. La propriété DisplayMember n’a pas besoin d’être définie.Then the DisplayMember property doesn't need to be set. Toutefois, si la source est plus compliquée, définissez DisplayMember sur le nom de la propriété ou de la colonne à partir de laquelle récupérer les sélections possibles.But if the source is more complicated, set DisplayMember to the name of the property or column from which to retrieve possible selections.

Si DataSource a la valeur d’un tableau de chaînes, ValueMember et DisplayMember n’ont pas besoin d’être définis, car chaque chaîne du tableau sera utilisée à la fois pour la valeur et pour l’affichage.If DataSource is set to a string array, then ValueMember and DisplayMember do not need to be set because each string in the array will be used for both value and display.

La modification de la propriété DataSource amène la cellule à réinitialiser sa collection Items et à se redessiner.Changing the DataSource property causes the cell to reinitialize its Items collection and redraw itself.

Lorsque vous modifiez la valeur de la propriété DataSource, le contrôle tente d’utiliser les valeurs de propriété ValueMember et DisplayMember avec la nouvelle source de données, et affecte à chaque propriété la valeur null si sa valeur est introuvable.When you change the value of the DataSource property, the control attempts to use the ValueMember and DisplayMember property values with the new data source, and sets each property to null if its value cannot be found. Toute exception qui se produit pendant ce processus est ignorée sauf s’il s’agit de l’une des exceptions critiques suivantes : NullReferenceException, StackOverflowException, OutOfMemoryException, ThreadAbortException, ExecutionEngineException, IndexOutOfRangeExceptionou AccessViolationException.Any exception that occurs during this process is ignored unless it is one of the following critical exceptions: NullReferenceException, StackOverflowException, OutOfMemoryException, ThreadAbortException, ExecutionEngineException, IndexOutOfRangeException, or AccessViolationException.

Lorsque le DataSource est défini, le DataGridViewComboBoxCell est attaché à l’événement Disposed de la source de données.When the DataSource is set, the DataGridViewComboBoxCell attaches to the Disposed event of the data source. Lorsque le DataGridViewComboBoxCell est détaché du DataGridView, la ressource n’est pas libérée immédiatement.When the DataGridViewComboBoxCell is detached from the DataGridView, the resource is not immediately released. La ressource DataGridViewComboBoxCell est libérée lorsque la source de données attachée est supprimée.The DataGridViewComboBoxCell resource is released when the attached data source is disposed. Pour libérer immédiatement la ressource pour garbage collection, affectez à la propriété DataSource la valeur null.To release the resource for garbage collection immediately, set the DataSource property to null.

S’applique à

Voir aussi