如何使只有一个方法来填充ComBobox和ListBox的项



下面的过程用数据库中的值填充组合框。

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

两个项目集合都实现IList

因此,不必传递ComboBox/ListBox,只需将comboBox1.Items或listBox1.Items传递给方法即可。

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

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

您可以使用@Holger答案。

对于速度性能,您可以使用重构的

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

用法:

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

我将重新构造此代码。您试图在1个函数中执行太多操作。

将从DB获取与操作控件分离。现在GetDbItems函数是独立的-更容易移动到单独的类&不直接绑定到UI。

类似这样的东西:

IList<string> items = GetDbItems("a", "b", "c");
if (items.Any())
{
control.Items.Clear();
control.Items.Add(items);
}
private IList<string> GetDbItems(string select, string from, string order = "")
{
var result = new List<string>();
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();
while (dataReader.Read())
{
result.Add(dataReader[select]);
}
}
}
return result;
}
  • 这只是在编辑框中键入的-我不能保证它会编译。我只是想让你领先一步

相关内容

  • 没有找到相关文章