callum.bennett
callum.bennett

Reputation: 686

HTML elements in C#

HtmlAnchor[] anchorToConvert = new HtmlAnchor[]{
    clickHere,
leavePage};

Button[] buttonToConvert = new Button[]{
    login,
register};

i = 0;
for (i = 0; i < anchorToConvert.Length; i++)
{
    DataRow[] result = ds.Tables[0].Select("htmlControl LIKE '" + anchorToConvert[i].ID.ToString() + "'");

    if (result.Length > 0)
    {
        anchorToConvert[i].InnerHtml = result[0]["phrase"].ToString();
    }
}
i = 0;
for (i = 0; i < buttonToConvert.Length; i++)
{
    DataRow[] result = ds.Tables[0].Select("htmlControl LIKE '" + buttonToConvert[i].ID.ToString() + "'");

    if (result.Length > 0)
    {
        buttonToConvert[i].Text = result[0]["phrase"].ToString();
    }
}

I have two arrays of html elements i need to loop through, and use the elements id attribute to select content from a database. Rather than having to create two arrays and loop through them individually, is there someway i can make a more generic array that can contain both buttons and anchors?

Upvotes: 0

Views: 536

Answers (2)

Sir Belmalot
Sir Belmalot

Reputation: 98

You could use a list and check the type of the control in the list when you're looping through:

List<Control> ctrl = new List<Control>();
HtmlAnchor anchor = new HtmlAnchor();
anchor.ID = "myAnchor";
ctrl.Add(anchor);

Button btn = new Button();
btn.ID = "MyBtn";

ctrl.Add(btn);

foreach (Control c in ctrl.ToList())
{
    if (c is Button)
    {
        // Do Something
    }
}

Upvotes: 3

Oded
Oded

Reputation: 499062

Both HtmlAnchor and Button inherit from Web.UI.Control (though not directly).

If that is the type of the array, both of these types (HtmlAnchor and Button) can be assign to the array.

Upvotes: 1

Related Questions