Live Chat Icon For mobile
Live Chat Icon

How can you use a ListBox control to display items with Price above a specific value in one color and the ones below that value in a different color

Platform: ASP.NET| Category: ListBox

The ListBox Web server control prevents us from assigning the style property to each item in the ListBox. This bug is confirmed by Microsoft Knowledge Base Article – 309338

So, instead use a HTML ListBox with runat=server


<SELECT id='listbox1' size='14' runat='server' >
</SELECT>

VB.NET


Dim myconnection As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	myconnection = New SqlConnection('Server=localhost;uid=sa;password=;database=northwind;')
	myda = New SqlDataAdapter('Select * from Products ', myconnection)
	ds = New DataSet()
	myda.Fill(ds, 'AllTables')
	dim i as Integer
	For i = 0 To ds.Tables(0).Rows.Count - 1
		listBox1.Items.Add(New ListItem(ds.Tables(0).Rows(i)('UnitPrice'), ds.Tables(0).Rows(i)('ProductID')))
		If ds.Tables(0).Rows(i)('UnitPrice') <= 25 Then
			listBox1.Items(i).Attributes.Add('style', 'color:red')
		Else
			listBox1.Items(i).Attributes.Add('style', 'color:green')
		End If
	Next
End Sub

C#


SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
	if (!IsPostBack)
	{
		strConn='Data Source=localhost;uid=sa;pwd=;Initial Catalog=northwind';
		mycn = new SqlConnection(strConn);
		myda = new SqlDataAdapter ('Select * FROM Products ', mycn);
		ds = new DataSet();
		myda.Fill (ds,'Table');
				
		for(int i = 0 ;i < ds.Tables[0].Rows.Count - 1;i++)
		{
			listBox1.Items.Add (new ListItem(ds.Tables[0].Rows[i]['UnitPrice'].ToString(),
			ds.Tables[0].Rows[i]['ProductID'].ToString()));
			if(Convert.ToDouble(ds.Tables[0].Rows[i]['UnitPrice'].ToString()) <= 25 )
			{
				listBox1.Items[i].Attributes.Add('style', 'color:red');
			}
			else
			{
				listBox1.Items[i].Attributes.Add('style', 'color:green');
			}
		}
	}
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.