1

I have about 65 textbox fields in my ASP.NET form. Instead of adding all parameters to SqlCommand one by one, I want to do like this.

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 ); 
    }
}

Is it a good idea to use FindControl method when considering performance for this type of scenario.

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Yesudass Moses
  • 1,841
  • 3
  • 27
  • 63
  • 2
    Don't know if there is a real performance impact due to FindControl. But I could suggest something else : if all Textboxes are in a common container, you can also loop other them using its Controls property. It avoids use of FindControl and doesn't require anymore the fields[] variable. – AFract Apr 15 '15 at 12:58

1 Answers1

1

Instead of finding all the textboxes from your page you can only loop through the textbox controls like this:-

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

But I am really note sure how much of performance gain you will get out of it when compared to that of FindControl.

Also, as @AFract mentioned since Control collection is not recursive, to get all the controls recursively you can use this very helpful extension method:-

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);
}

Borrowed from Here.

Community
  • 1
  • 1
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
  • 1
    It's what I've also suggested in my comment. One thing to know : Controls collection is not recursive, so if Textboxes are not directly in Page itself, they won't be found. But this could easily be fixed. – AFract Apr 15 '15 at 13:00
  • @AFract - Yeah Exactly. – Rahul Singh Apr 15 '15 at 13:01