Sunday, March 1, 2009

Usefull functions...

I seems that in every project there is a set of functions that I use.
For that reason, I've decided to place them here so I won't need to search for them any more.
The functions are:

// Finding a control recursively
public static Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }
    foreach (Control ctrl in root.Controls)
    {
        Control c = FindControlRecursive(ctrl, id);
        if (c != null)
        {
            return c;
        }
    }
    return null;
}

// Generate random
public static Random GenerateRandom()
{
    Guid _temp = Guid.NewGuid();
    int _i = 0;
    byte[] bytes = _temp.ToByteArray();
    for (int i = 0; i < bytes.Length; i++)
        _i += (int)bytes[i];

    return new Random(_i);
}

// RenderControl into HTML
public static string RenderControl(Control ctrl)
{
    StringBuilder sb = new StringBuilder();
    StringWriter tw = new StringWriter(sb);
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    ctrl.RenderControl(hw);
    return sb.ToString();
}

1 comment:

  1. As for GenerateRandom method, my version is:

    return new Random(Guid.NewGuid().GetHashCode());

    Works like a charm :-)

    ReplyDelete