Search code examples
c#winformscomboboxlistboxdry

How to make only one method to populate Items of a ComBobox as well as a ListBox?


This procedure below fills a ComboBox with values from a database.

There is also one for ListBoxes, and it's completely identical except "box" is a ListBox.

Both CB and LB classes have Items and both inherit ListControl which doesn't have Items.

How can I get rid of the duplicate code there?

private void UpdateBox (ComboBox box, string select, string from, string order = "")
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        if (order == "") order = select;
        using (SqlCommand command = new SqlCommand("SELECT " + select +
            " FROM " + from + " ORDER BY " + order, conn))
        {
            SqlDataReader dataReader = command.ExecuteReader();
            box.Items.Clear();
            while (dataReader.Read())
            {
                box.Items.Add(dataReader[select]);
            }
        }
    }
}

Here is the other one:

private void UpdateBox (ListBox box, string select, string from, string order = "")
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        if (order == "") order = select;
        using (SqlCommand command = new SqlCommand("SELECT " + select +
            " FROM " + from + " ORDER BY " + order, conn))
        {
            SqlDataReader dataReader = command.ExecuteReader();
            box.Items.Clear();
            while (dataReader.Read())
            {
                box.Items.Add(dataReader[select]);
            }
        }
    }
}

Solution

  • Both Items Collections implement IList

    So instead of passing the ComboBox/ListBox, you can just pass comboBox1.Items or listBox1.Items to your method.

     private void UpdateBox (IList items, string select, string from, string order = "")
    

    ...

     items.Clear();
     while (dataReader.Read())
     {
         items.Add(dataReader[select]);
     }