Populate ComboBox using DataTable

C# code snippet - How to populate data in a ComboBox using DataTable

C# code snippet - How to populate data in a ComboBox using DataTable

C++/CLI code snippet CreateDropDownMenu to populate ComboBox dropdown menu with given DataTable.

Bookmark:

Populate ComboBox using DataTable

This C++/CLI code snippet populate UI ComboBox with given DataTable. Simply pass ComboBox UI object , DataTable with values, DataTable Value field name and DataTable display field name. Using given DataTable fields this function will populate ComboBox dropdown menu. Optionally you can pass default display value to be displayed when ComboBox data populated. DataTable can be generated using a Database or by manually creating static data.

/// <summary>
/// Creates the drop down menu.
/// </summary>
/// <param name="_tmpComboBox">The combo box.</param>
/// <param name="_DataSource">The datasource.</param>
/// <param name="_ValueMember">The value member.</param>
/// <param name="_DisplayMember">The display member.</param>
/// <param name="_DefaultDisp">The default display value (Optional).</param>
void CreateDropDownMenu(ComboBox ^%_tmpComboBox, DataTable ^_DataSource, System::String ^_ValueMember, System::String ^_DisplayMember, System::String ^_DefaultDisp)
{
    if (_DataSource != nullptr)
    {
        // Set display, value options
        _tmpComboBox->ValueMember = _ValueMember;
        _tmpComboBox->DisplayMember = _DisplayMember;

        // Create custom row
        if (_DefaultDisp != nullptr)
        {
            DataRow ^_row = _DataSource->NewRow();
            _row[1] = _DefaultDisp;
            _row[0] = 0;

            // Insert Custom row at beginning
            _DataSource->Rows->InsertAt(_row, 0);
        }

        _tmpComboBox->DataSource = _DataSource;
        _tmpComboBox->SelectedIndex = 0;
    }
}
void CreateDropDownMenu(ComboBox ^%_tmpComboBox, DataTable ^_DataSource, System::String ^_ValueMember, System::String ^_DisplayMember)
{
    CreateDropDownMenu(_tmpComboBox, _DataSource, _ValueMember, _DisplayMember, nullptr);
}


Here is a simple example showing how to use above function (CreateDropDownMenu) to populate ComboBox drop down menu with values.

 
DataTable ^_DataTable = ... Apply your methods to populate DataTable ...

CreateDropDownMenu(ref comboBox1, _DataTable, "VALUE_FIELD_NAME", "DISPLAY_FIELD_NAME", " - Select - ");

- or -

CreateDropDownMenu(ref comboBox1, _DataTable, "VALUE_FIELD_NAME", "DISPLAY_FIELD_NAME");


C++/CLI Keywords Used:

  • DataTable
  • ComboBox
  • DataRow
  • ValueMember
  • DisplayMember

Code Snippet Information:

  • Applies To: .Net, C++/CLI, CLI, SQL, DataTable, SQL Server, SQL Client, ComboBox, Drop down menu
  • Programming Language : C++/CLI

External Resources:

Leave a comment