简体   繁体   English

C#Winforms-数据绑定或列表<T>

[英]C# Winforms - Databinding or List<T>

I have here a method inside a class called PurchaseOrder. 我在一个名为PurchaseOrder的类中有一个方法。 Here, I used List<string> to retrieve a list of suppliers and populate these lists in a combo box. 在这里,我使用List<string>检索供应商列表,并在组合框中填充这些列表。 The code actually works, but as I add more and more suppliers in my SQL Server database, I have been experiencing a little slowdown on the forms being loaded. 该代码实际上有效,但是随着我在SQL Server数据库中添加越来越多的供应商,我在加载的表单上遇到了一些放慢的感觉。 How could I optimize such speed? 我如何优化这种速度?

Below are two sets of codes, the method PopulateSuppliers() from PurchaseOrderClass.cs and a Form_Load event. 以下是两组代码,PurchaseOrderClass.cs中的PopulateSuppliers()方法和Form_Load事件。

    public object PopulateSuppliers()
    {
        //Create an instance of a List of Strings.
        List<string> ListOfSuppliers = new List<string>();

        string sqlString = "SELECT CompanyName FROM tbl_suppliers WHERE Archived = 'False';";

        SqlConnection sqlConnection = new SqlConnection(connectionString);
        SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection);

        sqlConnection.Open();
        sqlReader = sqlCommand.ExecuteReader();

        while (sqlReader.Read())
        {
            ListOfSuppliers.Add(sqlReader["CompanyName"].ToString());
        }

        sqlReader.Close();
        sqlConnection.Close();

        return ListOfSuppliers;
    }

    private void frmPurchaseOrderEditor_Load(object sender, EventArgs e)
    {
        ...

        //Populate a list of suppliers.
        cboSuppliers.DataSource = PurchaseOrder.PopulateSuppliers();

        ...
    }

Maybe creating an index on the Archived column might help.. But your code looks fine. 也许在“存档”列上创建索引可能会有所帮助。。但是您的代码看起来不错。 However, if the list of suppliers is going to keep growing, think about the chances of replace your combo with a paged datagrid. 但是,如果供应商列表将保持增长,请考虑用分页数据网格替换您的组合的机会。

Also, always use a finally block when working with DDBB and dispose Commands and Connection classes there to release unmanaged resources. 另外,在使用DDBB时,请始终使用finally块,并在其中放置Commands和Connection类以释放非托管资源。

Your code is perfectly fine i think...but if the data in the table is too much, then i don't think that combo box is the best option for you..try other alternatives...like GridView, ListView, Repeater...and there is always the client side. 我认为您的代码非常好...但是,如果表中的数据太多,那么我认为组合框不是您的最佳选择..尝试其他替代方法...例如GridView,ListView,Repeater ...而且总是有客户端。

When using any resource such as SqlReader, File, etc (All the classes library types which uses IDisposable interface) you should use "using" statement which will take care of allocating as well disposing of the resource... 当使用诸如SqlReader,File等(使用IDisposable接口的所有类库类型)之类的任何资源时,应使用“ using”语句,该语句将负责资源的分配以及处置。

click here for more info on using statement 单击此处以获取有关using语句的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM