我们可以像这样将控件作为方法参数传递:
private void FillComboBox(ComboBox combobox)
{
if ( combobox == null ) return; // Or throw new Exception...
Con.Open();
SqlCommand cmd = new SqlCommand("select CatName from CategoryTbl", Con);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("CatName", typeof(string));
dt.Load(rdr);
combobox.ValueMember = "catName";
combobox.DataSource = dt;
Con.Close();
}
我们这样称呼:
FillComboBox(myComboBox);
因此,我们可以根据所提供代码的逻辑填充我们想要的任何组合,拥有自己的 DataSource 到自己的 DataTable。
可能会改进和重构为不执行查询并为每个组合创建一个表:
private const string CategoryColumnName = "CatName";
private DataTable CategoryLookupTable = new DataTable();
private void InitializeCategoryLookupTable()
{
if ( Connection == null ) return; // Or throw new Exception...
Connection.Open();
try
{
using ( var command = new SqlCommand("select CatName from CategoryTbl", Connection) )
using ( var reader = command.ExecuteReader() )
{
CategoryLookupTable.Columns.Add(CategoryColumnName, typeof(string));
CategoryLookupTable.Load(reader);
}
}
finally
{
Connection.Close();
}
}
private void FillFromCategoryLookupTable(ComboBox combobox)
{
if ( combobox == null ) return; // Or throw new Exception...
if ( combobox.DataSource == CategoryLookupTable ) return;
combobox.DataSource = null;
combobox.ValueMember = CategoryColumnName;
combobox.DataSource = CategoryLookupTable;
}
因此,我们将在某处调用InitializeCategoryLookupTable(例如在表单加载或显示事件处理程序中),然后再调用FillFromCategoryLookupTable:
private void MyForm_Load(object sender, EventArgs e)
{
InitializeCategoryLookupTable();
FillFromCategoryLookupTable(myFirstComboBox);
}
如果需要不同的源和列名,可以通过将它们作为参数传递来以相同的方式进行重构:
private DataTable CreateLookupTable(string nameTable, string nameColumn)
{
if ( Connection == null ) return null;
Connection.Open();
try
{
using ( var command = new SqlCommand($"select {nameColumn} from {nameTable}", Connection) )
using ( var reader = command.ExecuteReader() )
{
var table = new DataTable();
table.Columns.Add(nameColumn, typeof(string));
table.Load(reader);
return table;
}
}
finally
{
Connection.Close();
}
}
private void FillFromLookupTable(ComboBox combobox, DataTable table, string column)
{
...
}