简体   繁体   中英

asp.net c# optimizing code

just feeling that i'm wasting loops here = CPU time, and was wondering if there's a way to optimize this code, or just minimize it.

Basically what the code does is, goes trough every controls inside the editOkkInfo control. checking if the current control is an textbox, if yes, then it will perform some stuff, if no it will jumps to next if-statement. This next statement checks if we have counted 14 times(since i only have 14 textboxes), if not 14, then the loop continues, if counted 14, then the loop breaks.

Any help is appreciated, thanks in advance, and here is the code, cheers.

iterate = 0;
foreach (System.Web.UI.Control ctrl in this.editOkkInfo.Controls)
{
    if (ctrl is TextBox)
    {
        tb = (TextBox)this.FindControl(ctrl.ClientID.ToString());
        tb.Text = dt.DefaultView[0][iterate++].ToString();
    }
    if (iterate == 14)
       break;
}

There is no need to use FindControl , as you already have the control. Just cast it:

iterate = 0;

foreach (System.Web.UI.Control ctrl in this.editOkkInfo.Controls)
{
    if (ctrl is TextBox)
    {
        tb = (TextBox)ctrl;
        tb.Text = dt.DefaultView[0][iterate++].ToString();
    }

    if (iterate == 14)
        break;
}

An additional readability improvement will do away with the looping over all controls and the is test:

foreach (TextBox ctrl in this.editOkkInfo.Controls)
{
    ctrl.Text = dt.DefaultView[0][iterate++].ToString();

    if (iterate == 14)
        break;
}

You can save your FindControl() parsing by casting the ctrl variable:

tb = (TextBox) ctrl;
tb.Text = //...

And, we should know if editOkkInfo.Controls are created by code or declared in aspx page. If the former is true, you can save a reference to such objects in a variable, then using it instead of looping.

if (ctrl is TextBox)
{
    tb = (TextBox)ctrl;
}

this should be enough, you are looking the TextBox using FindControl , knowing that you have it.So, you can just cast the the control to TextBox

I have seen one faster way to find all controls of specific type rather than looping. This seems more efficient. Using linq to get list of web controls of certain type in a web page Hope that helps Milind

我认为反而foreach会更好一些,因为一会儿不会检查所有控件,直到数量为14为止(能否检查所有控件,取决于!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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