首页 > 解决方案 > 如何只使用一种方法来填充 ComBobox 和 ListBox 的项目?

问题描述

下面的过程用数据库中的值填充 ComboBox。

ListBoxes 也有一个,除了“box”是一个 ListBox 之外,它完全一样。

CB 和 LB 类都有 Items,并且都继承了没有 Items 的 ListControl。

我怎样才能摆脱那里的重复代码?

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

这是另一个:

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

标签: c#winformscomboboxlistboxdry

解决方案


两个项目集合都实现了 IList

因此,您可以将 comboBox1.Items 或 listBox1.Items 传递给您的方法,而不是传递 ComboBox/ListBox。

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

...

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

推荐阅读