c# - 如何只使用一种方法来填充 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]);
}
}
}
}
解决方案
两个项目集合都实现了 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]);
}
推荐阅读
- typescript - Zone.js 检测到 ZoneAwarePromise `(window|global).Promise` 已在 Angular 8 中被覆盖
- linux - 从具有不同结尾的文件中获取具体的 URL
- html - 将数据从 HTML 页面传递到打字稿文件
- matlab - 使用matlab计算n次(或更少)次伯努利试验中成功的概率
- typescript - 有什么区别?或 / 在 http 请求中
- angular - Angular 材质自定义输入 - 从外部调用 setValidator 时移除内部验证器
- arrays - if(temp_similarity[k]==similarity[l]): ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()
- java - 启动、更新 AWS IOT 作业的权限
- vb6 - VB6:如何强制光标进入文本框但释放按钮按下
- c++ - 如何在不使用套接字的情况下在 C++ 中发送 POST 请求