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-Sharp) C# code snippet CreateDropDownMenu to populate ComboBox dropdown menu with given DataTable.

Bookmark:

Populate ComboBox using DataTable

This .Net C# 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>
public void CreateDropDownMenu(ref ComboBox _tmpComboBox, DataTable _DataSource, string _ValueMember, string _DisplayMember, string _DefaultDisp)
{
    if (_DataSource != null)
    {
        // Set display, value options
        _tmpComboBox.ValueMember = _ValueMember;
        _tmpComboBox.DisplayMember = _DisplayMember;

        // Create custom row
        if (_DefaultDisp != null)
        {
            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;
    }
}
public void CreateDropDownMenu(ref ComboBox _tmpComboBox, DataTable _DataSource, string _ValueMember, string _DisplayMember)
{
    CreateDropDownMenu(ref _tmpComboBox, _DataSource, _ValueMember, _DisplayMember, null);
}


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# Keywords Used:

  • DataTable
  • ComboBox
  • DataRow
  • ValueMember
  • DisplayMember

Code Snippet Information:

  • Applies To: .Net, C#, CLI, SQL, DataTable, SQL Server, SQL Client, ComboBox, Drop down menu
  • Programming Language : C# (C-Sharp)

External Resources:

Leave a comment