views:

13

answers:

1

I have a DropDownList on an ASP.NET page that gets populated by a SQL database.

<asp:DropDownList ID="ddlName" runat="server"></asp:DropDownList>

The population is down in the code behind file:

ddlName.DataSource = SqlDataSource1;
ddlName.DataValueField = (this.ddlName.SelectedValue);
ddlName.DataTextField = "ccName";
ddlName.DataBind();

I was wondering if it was possible to change the background or text color of an item in the list based on it's value?


I just noticed that the example below works when the page first loads but on postback the text color disappears even though that is where the code is. Is there something I am missing?

protected override void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            ddlName.DataSource = SqlDataSource5;
            ddlName.DataValueField = (this.ddlName.SelectedValue);
            ddlName.DataTextField = "ccName";
            ddlName.DataBind();


            foreach (ListItem item in ddlName.Items)
            {
                if (item.Value == "Item 1")
                {
                    item.Attributes.Add("style", "color:red");
                }

                if (item.Value == "Item 2")
                {
                    item.Attributes.Add("style", "color:red");
                }
            }

        }

    }
A: 

Yup you sure can, add this to your page load event.

foreach(ListItem item in ddlName.Items) {
    if(item.Value == "someStringValue") {
        item.Attributes.Add("style", "color:red")
    }
}

If that doesn't work, you can move this code to the DataBound event of the Drop Down List.

Marko
That worked perfectly. Thanks!
Brett