Johan
Johan

Reputation: 35194

Find element by attribute in aspx

<div id="foo" runat="server" data-id="bar"></div>

In the code behind, this div can be accessed either directly on the id or using FindControl().

But is there any way to search for elements on an aspx based on another attribute than id? Like data-id="bar" above for example.

Upvotes: 5

Views: 3648

Answers (2)

Alex Filipovici
Alex Filipovici

Reputation: 32561

This extension method (which uses recursion) might be helpful:

public static IEnumerable<Control>
    FindControlByAttribute(this Control control, string key)
{
    var current = control as System.Web.UI.HtmlControls.HtmlControl;
    if (current != null)
    {
        var k = current.Attributes[key];
        if (k != null)
            yield return current;
    }
    if (control.HasControls())
    {
        foreach (Control c in control.Controls)
        {
            foreach (Control item in c.FindControlByAttribute(key, value))
            {
                yield return item;
            }
        }
    }
}

Sample usage:

protected void Page_Load(object sender, EventArgs e)
{
    var controls = this
        .FindControlByAttribute("data-id")
        .ToList();
}

If you also want to filter by the value:

public static IEnumerable<Control>
    FindControlByAttribute(this Control control, string key, string value)
{
    var current = control as System.Web.UI.HtmlControls.HtmlControl;
    if (current != null)
    {
        var k = current.Attributes[key];
        if (k != null && k == value)
            yield return current;
    }
    if (control.HasControls())
    {
        foreach (Control c in control.Controls)
        {
            foreach (Control item in c.FindControlByAttribute(key, value))
            {
                yield return item;
            }
        }
    }
}

Upvotes: 6

Ahmed ilyas
Ahmed ilyas

Reputation: 5822

you would need to see what the attributes are for that control you iterate through in the FindControl or if you are accessing the element directly like so:

this.foo

then you can use the Attributes collection to see what the specified attribute value is. http://msdn.microsoft.com/en-us/library/kkeesb2c(v=vs.100).aspx

but to answer your question - no, there is not unless you iterate a container/parent control using FindControl()

Upvotes: 0

Related Questions