控件动态设置颜色

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

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:

<SELECT id="DropDownList1" name="DropDownList1" runat="server"></SELECT>

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.
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 CategoryTable ", mycn);
		ds = new DataSet();
		myda.Fill (ds,"Table");
				
		DropDownList1.DataSource =ds.Tables [0] ;
		DropDownList1.DataTextField =ds.Tables[0].Columns["CategoryName"].ColumnName.ToString();
		DropDownList1.DataValueField =ds.Tables[0].Columns["CategoryId"].ColumnName.ToString();
		DropDownList1.DataBind () ;
 
		for (int i =0;i < DropDownList1.Items.Count ;i++ )
		{		 
			DropDownList1.Items[i].Attributes.Add("style", "color:" + ds.Tables[0].Rows[i]["CategoryColor"].ToString () );
		}
	}
}

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 CategoryTable ", myconnection)
	ds = New DataSet()
	myda.Fill(ds, "AllTables")
	
	DropDownList1.DataSource = ds
	DropDownList1.DataSource = ds.Tables(0)
	DropDownList1.DataTextField = ds.Tables(0).Columns("CategoryName").ColumnName.ToString()
	DropDownList1.DataValueField = ds.Tables(0).Columns("CategoryId").ColumnName.ToString()
	DropDownList1.DataBind()
	
	Dim i As Integer
	For i = 0 To DropDownList1.Items.Count - 1
		DropDownList1.Items(i).Attributes.Add("style", "color:" + ds.Tables(0).Rows(i)("CategoryColor").ToString())
	Next
End Sub

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:

 

Tag that we use:

<SELECT id="listBox1" size="10" runat="server"></SELECT>

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:

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");
			}
		}
	}
}

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

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:

So the control we use is

<SELECT id="DropDownList1" name="DropDownList1" runat="server"></SELECT>

And code for this is as below:

Method 1:

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

C#
using System.Reflection;
VB.NET
Imports System.Reflection

 

C#
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
	foreach(FieldInfo col in typeof(KnownColor).GetFields() )
	{
	if (col.FieldType == typeof(KnownColor) )
		{
		DropDownList1.Items.Add(new ListItem(col.Name ,col.Name));
		}
	}  
}
for (int i= 0 ;i < DropDownList1.Items.Count;i++)
	{
		DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);
	}
}
VB.NET
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
Dim col As FieldInfo
For Each col In GetType(KnownColor).GetFields
	If col.FieldType Is GetType(Drawing.KnownColor) Then
		DropDownList1.Items.Add(New ListItem(col.Name, col.Name))
	End If
Next
End If

Dim i As Integer
For i = 0 To DropDownList1.Items.Count - 1
	DropDownList1.Items(i).Attributes.Add("style", "background-color:" + DropDownList1.Items(i).Text)
Next
End Sub

Method 2:

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

C#
using System.ComponentModel;
VB.NET
Imports System.ComponentModel

 

C#
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
	foreach(Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues())
	{
		ListItem li = new ListItem();
		li.Text = TypeDescriptor.GetConverter(c).ConvertToString(c);
		this.DropDownList1.Items.Add(li);
	}
}
for (int i= 0 ;i < DropDownList1.Items.Count;i++)
	{
		DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);
	}
}
VB.NET
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
Dim c As Color
For Each c In TypeDescriptor.GetConverter(GetType(Color)).GetStandardValues()
	Dim li As New ListItem()
	li.Text = TypeDescriptor.GetConverter(c).ConvertToString(c)
	Me.DropDownList1.Items.Add(li)
Next c
End If

Dim i As Integer
For i = 0 To DropDownList1.Items.Count - 1
	DropDownList1.Items(i).Attributes.Add("style", "background-color:" + DropDownList1.Items(i).Text)
Next
End Sub

posted on 2006-09-03 10:49  石川  阅读(347)  评论(0)    收藏  举报