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

excel vba populate listbox with multiple columns
listbox add item
excel vba combobox selected item
c# combobox add item and value
how to add items in combobox in vb
populate listbox vba
combobox add item c#
listbox lines between items vba

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]);
            }
        }
    }
}

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]);
 }

Populate Userform Listbox or Combobox, Populate Useform LostBox or Combobox — Numerous techniques for 1. See my Create & Employ a Userform tips page for information on creating A listbox provides users with a convenient means of selecting one or more items from a fixed pre-defined list. The "AddItem" method is well suited for a short simple list. A listbox provides users with a convenient means of selecting one or more items from a fixed pre-defined list. A combobox provides users with a compact and convenient means of selecting a single item from a pre-defined list. A combobox can be configured to accept pre-defined list entries only or allow the user to enter his or her own text.

You can use @Holger answer.

For speed performances you can use that refactored:

private void PopulateItems(List<IList> listItems,
                           string column,
                           string table,
                           string orderByColumn = "")
{
  using ( var connection = new SqlConnection(connectionString) )
  {
    connection.Open();
    if ( orderByColumn == "" )
      orderByColumn = column;
    string sql = $"SELECT {column} FROM {table} ORDER BY {orderByColumn}";
    using ( var command = new SqlCommand(sql, connection) )
    {
      var reader = command.ExecuteReader();
      foreach ( var items in listItems )
        items.Clear();
      while ( reader.Read() )
        foreach ( var items in listItems )
          items.Add(reader[column]);
    }
  }
}

Usage:

var listItemsToPopulate = new List<IList>()
{
  comboBox1.Items,
  listBox1.Items
};

PopulateLists(listItemsToPopulate, "", "", "");

Add and Remove Items from ComboBox, ListBox, or , Learn how to add and remove a Windows Forms ComboBox, ListBox, Add the string or object to the list by using the Add method of the ObjectCollection class. Remove has one argument that specifies the item to remove. If you can't write the items in 1 go into the combobox/listbox you'd better store them in an array first. When ready you can assign the array to the combobox/listbox. That's the most efficient way to populate. 0.2.5 Column. The method Column is identical to the method List. There is 1 exception: the array that is being written to the listbox/combobox will be transposed: rows will become columns, columns will be converted into rows.

Combo box and list box, If you have the XAML Controls Gallery app installed, click here to open the app and You populate the combo box by adding objects directly to the Items Selector, so you can get the user's selection in the same standard way. contain only 1 item because combo box does not support multiple selection. ' ----- ' Purpose: Populate listbox items from a horizontal data-set ' ----- Sub rangeHorizontal() Dim rngHorizontal As Range Dim cell As Range 'Define source range Set rngHorizontal = ThisWorkbook.Worksheets("ListBoxFromRange").Range("numbersHorizontal") 'Loop through the range and add cells to the listbox For Each cell In rngHorizontal

VBA Controls - ComboBox, ComboBox - This control allows the user to either select an item from the to a listbox although a combobox is a drop-down box and it displays only one item at a time. You can use the "AddItem" method when you have a single column combobox. If you try to add items to a combobox that has a non empty RowSource´┐Ż One: Only one item can be selected. MultiSimple: Multiple items can be selected. MultiExtended: Multiple items can be selected, and the user can use the SHIFT, CTRL, and arrow keys to make selections. To select an item in a ListBox, we can use the SetSelect method that takes an item index and a true or false value where the true value

1001 Things You Wanted to Know about Visual FoxPro, ListItemID = -1 You must then take action to add the new item to the control's RowSource. If the only requirement is to add a new description along with its primary key may also need to be populated when a new item is added to the combo box. the fact that there is no quick and easy way to add new items to a ListBox. How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control. 03/30/2017; 2 minutes to read +8; In this article. Items can be added to a Windows Forms combo box, list box, or checked list box in a variety of ways, because these controls can be bound to a variety of data sources.

VBA for smarties How to fill a Combobox / Listbox, Everything we'll discuss here applies to Comboboxes as well as Listboxes. I you set the property 'style' to 2 (dropdownlist) only the populated items can be chosen. The method Additem is meant to add exactly 1 item to a combobox/ listbox. If you use 'rowsource' you make a direct link to a certain range in a worksheet. We learn today how to populate a combobox with unique items using VBA and data from the Excel worksheet. Next we use two labels to display a message with the quantity available.

Comments
  • You may be able to do: combobox.Items.Add(dataReader[select]); listbox.Items.Add(dataReader[select]); in the loop. Can you put the duplicated code, please?
  • Updated the post. As for the suggestion, I could've done that if there were just as many CBs as LBs and I wanted to fill the them with the same data. Correct me if I'm wrong
  • Just tried this. IList doesn't seem to work without "<T>". I tried "IList<object> items". When I called it with "element.Items" it said "cannot convert from 'System.Windows.Forms.[ComboBox/ListBox].ObjectCollection' to 'System.Collections.Generic.IList<object>'". With "(Ilist<object>)element.Items" it compiled, but then threw a "System.InvalidCastException: Unable to cast Objects of type "ObjectCollection" to type "System.Collections.Generic.IList`1[System.Object]"."
  • There is System.Collections.IList, and System.Collections.Generic.IList<T>. You have not "using System.Collections", if IList is unknown. ObjectCollection implements IList, you can check. Hence you can cast to it.
  • *Another caveat, I don't know if this is just sample code you're posting, but I just wanted to mention that the way you're building the SQL query here is wide open to SQL injection. In production, you should really use parameters to build the query. Otherwise make sure you sanitize any user inputs.