Introduction: In this article you will see the coloring of list item's text in DropDownList at run time.
How can we change the color?
There are the following steps for coloring of list item's text in DropDownList.
Step 1: Open new web site in Microsoft Visual Studio 2005.
Step 2: Drag the DropDownList control on the page from the toolbox or you can write the following source code (inline code).
<asp:DropDownList ID="ddlStudent" runat="server"></asp:DropDownList>
Step 3: You can set some properties of the DropDownList control.
For Example: In this example I am setting some properties.
Default.aspx: The inline code is as follows:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>DDlist</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlStudent" Height="20px" Width="150px" runat="server" style="background-color: #ffcccc">
</asp:DropDownList>
</div>
</form>
</body>
</html>
Step 4: Establish the connection (pass the connection string).
Step 5: Now write the following code on the page load.
Default.aspx.vb:
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dr As SqlDataReader
Dim CONNECTION_STRING As String = "Data Source=MCN004;Initial Catalog=student;Integrated Security=True"
Dim sQuery As String = "select Rollno, Name, Course from student"
Dim cn As New SqlConnection(CONNECTION_STRING)
Dim cmd As New SqlCommand(sQuery, cn)
cn.Open()
dr = cmd.ExecuteReader
Do While dr.Read
Dim li As New ListItem(dr("Name"), dr("Course"))
Select Case dr("Rollno")
Case 1
li.Attributes.Add("style", "color:red")
Case 2
li.Attributes.Add("style", "color:Green")
Case 3
li.Attributes.Add("style", "color:voilet")
Case 4
li.Attributes.Add("style", "color:darkolivegreen")
Case Else
li.Attributes.Add("style", "color:fuchsia")
End Select
ddlStudent.Items.Add(li)
Loop
cn.Close()
End Sub
End Class
Step 6: Press F5 to debug the code.
Output: You will see the following output.

Figure 1: This page will display when you click on DropDownList.