添加 sqlparameter 时的 FindControl 性能

FindControl perfomance when adding sqlparameter

我的 ASP.NET 表单中有大约 65 个文本框字段。 我不想将所有参数一一添加到 SqlCommand,而是想这样做。

using (SqlCommand com = new SqlCommand(query, con))
{
    string[] fields = { "EmployeeID", "EmployeeNumber", "FirstName", "MiddleName", "LastName" };
    foreach (string fld in fields)
    {
        TextBox tb = (TextBox)Page.FindControl(fld); 
        com.Parameters.AddWithValue("@" + fld, tb.Text ); 
    }
}

在考虑此类场景的性能时,使用 FindControl 方法是个好主意吗?

您只能像这样遍历文本框控件,而不是从您的页面中查找所有文本框:-

foreach (TextBox textbox in Page.Controls.OfType<TextBox>())
{
            //Your Code here
}

但我确实注意到与 FindControl 相比,您将从中获得多少性能提升。

此外,正如@AFract 提到的,因为控件集合不是递归的,要递归地获取所有控件,您可以使用这个非常有用的扩展方法:-

public static IEnumerable<TControl> GetChildControls(this Control control) where TControl : Control
{
    var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>();
    return children.SelectMany(c => GetChildControls(c)).Concat(children);
}

借自 Here