通过数组将元素放入Listbox

时间:2015-01-21 14:03:21

标签: c# arrays winforms listbox

首先显示我的代码:

datTable = new DataTable();
sqlCmd = new SqlCommand("SELECT [CustomerId] FROM
[DataSource]", connection);
sqlDatAdapter = new SqlDataAdapter(sqlCmd.CommandText, connection);
            sqlDatAdapter.Fill(datTable);
            customer.DisplayMember = "CustomerId";
            customerListbox.DataSource = datTable;

这样可以很好地用SQL中的数据库中的列填充Listbox。我想做的是一个循环,他自动填充多个Listbox。它适用于带有SQL语句的循环但是如何处理行

customer.DisplayMember = "CustomerId"

有没有办法让我一遍又一遍地复制这段代码并手动更改这些代码?我尝试创建一个对象数组,并用customer.DisplayMember等填充它,但这不起作用。

我的意思是:我将不止一次地执行这段代码,每次只有Listbox和SQL列更改。因此,请使用不同的列填充不同的列表框。所以也许是一个数组或一个包含对象的列表 customer.DisplayMember,product.DisplayMember等

1 个答案:

答案 0 :(得分:0)

如果我理解你的意思,你想填充多个列表框。您可以通过传入列表框/数据成员和数据表的字典来创建填充所有列表框的方法。像这样:

    private void PopulateListBoxes(Dictionary<ListBox, string> ListBoxCollection, DataTable CustomerTable)
    {

        foreach(var key in ListBoxCollection.Keys)
        {
            key.DisplayMember = ListBoxCollection[key];
            key.DataSource = CustomerTable;
        }
    }

你可以这样打电话:

//this DataTable should contain data for all list boxes
sqlDatAdapter.Fill(dataTable);
Dictionary<ListBox, string> myListBoxes = new Dictionary<ListBox, string>();

//add your existing list boxes here with the corresponding data member
myListBoxes.Add(customerListBox, "CustomerID");
myListBoxes.Add(productListBox, "ProductID");
//add more here

PopulateListBoxes(myListBoxes, dataTable);