Search code examples
c#winformscomboboxdefault-value

C# Windows Forms ComboBox How to Set default value to "Select " initially loads data from datatable


I searched the site found several references to what I am looking to do. None worked in my case.

This seems like a simple problem. I am simply trying to set the default value to "--Select--".

I am filling the comboBox from a datatable from a database

        Admin_BL admBL = new Admin_BL();
        //populates datatable from database
        dtBlds = admBL.GetActiveBuildings();

        cmbBuilding.DataSource = dtBlds;
        cmbBuilding.Text = "--Select--";

        cmbBuilding.DisplayMember = "Building";
        cmbBuilding.ValueMember = "Building"; 

I have used this also:

cmbBuilding.Items.Insert(0, "Select Bld");

This seems like a simple task I am not sure why this is not working in windows forms I would appreciate the help Thank You!


Solution

  • The issue here is that you're binding to an object and that object does not contain an entry for "-- Select --". Either you need to add this entry during the query:

    SELECT 0 AS ID, '-- Select --' AS Building
    UNION ALL
    SELECT ID, BUILDING FROM <TABLE>
    

    Then when you bind you'll find "-- Select --" is the first item.

    If you don't want to change your query you can just insert a new row into the datatable once you've retrieved the data.

    Assuming you've only got 2 columns in your datatable (ID and Building):

    DataRow row = dtBlds.NewRow();
    row[0] = 0;
    row[1] = "-- Select --";
    dtBlds.Rows.InsertAt(row, 0);
    

    Once you've done this you can do the binding:

    cmbBuilding.DataSource = dtBlds;
    cmbBuilding.DisplayMember = "Building";
    cmbBuilding.ValueMember = "Building";