Refactor Code

  • Gravatar
    Reteriving Value from the textbox in placeholder control

    by nitinsomal@gmail.com on 5/8/2008 12:43:26 AM
  • Sir i have an place a textbox in place holder control and now i want to retreive the value from this textbox control in placeholder, how i can do this
  • If rblAction.SelectedValue = "Vendor" Then
    PlaceHolder1.Controls.Clear()

    ddl1.ID = "ddlVendor"
    PlaceHolder1.Controls.Add(ddl1)
    ElseIf rblAction.SelectedValue = "Add Vendor" Then
    PlaceHolder1.Controls.Clear()

    txt1.ID = "txtVendor"
    PlaceHolder1.Controls.Add(txt1)
    End If
  • Refactor it!
  • Gravatar
    Hi Nitin, Although this is not a refactoring question but anyways.. Can't you simply access the textbox by its names. It seems like your textbox is inside Contentplaceholder and you are using master pages!
    by azamsharp on 5/8/2008 7:04:58 AM

  • TextBox1.Text = "something"
  • Gravatar
    Here is a better find control method that you might find useful when searching for elements that are nested in other elements.
    by azamsharp on 5/8/2008 1:33:17 PM
  • public static class ExtensionMethods
    {

    public static T BetterFindControl<T>(this Control root, string id) where T : Control
    {
    if (root != null)
    {
    if (root.ID == id) return root as T;

    var foundControl = (T) root.FindControl(id);
    if (foundControl != null) return foundControl;

    foreach (Control childControl in root.Controls)
    {
    foundControl = (T) BetterFindControl<T>(childControl, id);
    if (foundControl != null) return foundControl as T;

    }
    }

    return null;
    }

    }
  • Gravatar
    linq query into the child controls of a placeholder (or of any container really).. you could get fancy and have a method where you supply a reference to the container, the type you want to filter by, and then the id to look for.. getVal(Control container, Type childType, string id)
    by bakasan on 5/10/2008 11:39:15 PM
  • public string getValue(PlaceHolder holder, string boxName)
    {
    //LINQ QUERY VERSION
    var vals = (from t in holder.Controls.OfType<TextBox>()
    where t.ID == boxName
    select t);

    //LINQ LAMBDA VERSION
    //var vals = holder.Controls.OfType<TextBox>().Select(t => t).Where(t => t.ID == boxName);

    return (vals.Any()) ? vals.First().Text : string.Empty;
    }
Please log in to refactor the code! Login