控件动态设置颜色

本文介绍如何在ASP.NET中根据不同条件为DropDownList和ListBox的项设置不同颜色,包括解决DropDownList设置项样式的问题,并提供了一种实现颜色选择器的方法。
Introduction:

This article is based on queries in the newsgroup:

Query 1 :"In my application i am using dropdownlist to display all categories from a table. When the user clicks this control I display all records in that category. Category table also contains column called color.
I wanted display some categories in dropdown list different color and others in different color using ASP.NET."-Anonymous

So data in the database along with the desired output is as given below

code36a.jpgcode36b.jpg

Note: The dropDownList has a bug which prevent us from assigning the style property to each item in the DropDownList.

This bug confirmed by Microsoft in Microsoft Knowledge Base Article - 309338  

So as stated by the MS Article the alternative method to achieve this is by using the tag given below:

Now our code.As far as coding the steps we would follow are as below:

  • Fill the DataSet
  • Populate the DropDownList with the DataSet
  • Navigate through the DropDownList to give appropriate color to each item in the dropdown.

Query 2 :"Is it possible for a listbox to show Products having Price above a specific value in one color and the ones below that value in different color"-Anonymous

To solve this the concept remains same only thing we need to do is use the ListBox and navigate through each and every record in dataset to have item with appropriate color. So lets consider the Products Table in Northwind Database and expect the output as below:

code36qa.jpgcode36qb.jpg

 

Tag that we use:

Coding Step:

  • Populate the dataset
  • Navigate through the Rows checking for the value in the DataBase and the specific value (in our case its set to 25)
  • Depending on the value assign the style property for each item in the ListBox

Code given below:

Sample Code

As we have done the coding for assigning style property to each item we might as well complete the code to develop a Color Picker in ASP.NET as below:

code36c.jpg

So the control we use is

And code for this is as below:

Method 1:

We'll use the namespace System.Reflection to get the FieldInfo (i.e. Colors)

 

Method 2:

The other way this can be done is by using Namespace System.ComponentModel and TypeDescripter Class.

 

转载于:https://www.cnblogs.com/hzuIT/articles/493532.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值