下面的此过程用数据库中的值填充组合框。
还有一个用于ListBoxes,它是完全相同,除了“ box”是一个ListBox。
CB和LB这两个类都具有Items,并且都继承了没有Item的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 clauseSelect,
string clauseFrom,
string clauseOrder = "")
{
using ( var connection = new SqlConnection(connectionString) )
{
connection.Open();
if ( clauseOrder == "" )
clauseOrder = clauseSelect;
string sql = $"SELECT {clauseSelect} FROM {clauseFrom} ORDER BY {clauseOrder}";
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[clauseSelect]);
}
}
}
用法:
var listItemsToPopulate = new List<IList>()
{
comboBox1.Items,
listBox1.Items
};
PopulateLists(listItemsToPopulate, "", "", "");