0

I have a listview and in It's ItemTemplate, a asp:panel which includes some controls. I need to apply three different css class to the asp:panel, depending on value of one of the controls in my asp:panel.

here's my code:

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        HiddenField type = (HiddenField)e.Item.FindControl("valueOfAd_type");
        HiddenField paid = (HiddenField)e.Item.FindControl("valueOfPayment");
        Panel ThePanel = (Panel)e.Item.FindControl("Panel1");
        if ( paid.Value == "2")
        {
            if (type.Value == "1")   //First condition
            {
                ThePanel.Attributes.Add("class", "whiteBackground");
            }
            else if (type.Value == "2")  //Second condition
            {
                ThePanel.Attributes.Add("class", "redBackground"); 
            }
        }
        else  //third condition
        {
            ThePanel.Attributes.Add("class", "blueBackground");
        }
    }
}

Problem is, no matter which condition occurs, always the last css class will be apply to all of my asp:panels. now my question is how to apply different css classes to asp:panels in different ItemTemplate?

Mahyar Kakaee
  • 82
  • 1
  • 3
  • 15
  • You should add the alternating item for your `ItemTemplate`. Why don't you try this comparison: `String.Compare(type.Value, "2") == 0)`? Also the panel should have `CssClass` attribute, for you to add to the Control. – Greg Oct 13 '15 at 14:37

1 Answers1

0

To better assist you, we would need the front-end syntax. That way we can see all of your Panel(s) that exist within the ItemTemplate. Based on your code it appears to be a single Panel.

Otherwise, I did notice the following:

  • You don't account for alternating item(s).
  • The comparison would be better, with String.Compare(...);.
  • Only one Panel is being called, which would be why only that one Panel color changes.

Also, you can simplify the code:

control.CssClass = "style";

You also stated that it always displays a blue background, I would verify that a value actually enters your initial if statement.

Greg
  • 11,302
  • 2
  • 48
  • 79