65.9K
CodeProject 正在变化。 阅读更多。
Home

为 ListBox 中的项目着色

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.19/5 (13投票s)

2004年8月31日

1分钟阅读

viewsIcon

194945

downloadIcon

2528

本文描述了 ASP.NET ListBox 中的“错误/特性”。

ColorListBox

引言

这是我的第一篇文章,而且非常简单。但是,我觉得有必要发布它,因为当我需要找到编程问题的答案时,我总是先来 CP,然后如果我在这里找不到答案,我就去 Google。几天前,我需要在 Web 上的 ListBox 中进行一些着色。我发现由于微软已知的一个“错误/特性”,我无法做到这一点。(KB 文章。)

因此,以下是在 VS.NET 2003 中解决此错误的步骤。

创建你的 ListBox

  1. 首先,你不需要使用 WebControl ListBox。相反,你需要使用 HTML Control ListBox
  2. 你需要右键单击 ListBox 并选择“作为服务器控件运行”,以便你可以从代码隐藏中使用此 ListBox
  3. 设置以下属性(可选):ID=ColorListBox1Size=8

现在你已经创建了 ListBox,但现在它还没有什么用,不是吗?接下来,我们将用一些数据填充它并更改一些颜色。

用数据填充 ListBox

我不会进行任何数据绑定,尽管你可以这样做。就我所知,这个 ListBox 现在就像普通的 WebControl ListBox 一样。转到你的代码隐藏并编辑 Page_Load 事件。添加以下代码行

ColorListBox1.Items.Clear(); //Clears the contents of the ListBox 

ListItem liRed = new ListItem("Red", "Red"); //Create a Red item
liRed.Attributes.Add("style", 
     "background-color: RED"); //Make the back color Red

ListItem liBlue = new ListItem("Blue", "Blue"); //Create a Blue item
liBlue.Attributes.Add("style", 
     "background-color: BLUE"); //Make the back color Blue

ListItem liGreen = new ListItem("Green", "Green"); //Create a Green item
liGreen.Attributes.Add("style", 
     "background-color: GREEN"); //Make the back color Green

//Add the items to the ListBox
ColorListBox1.Items.AddRange(new ListItem[]{liRed, liBlue, liGreen});

现在你完成了。如果你查看你的 aspx 页面,你应该会看到与上方图片相同的内容。

关注点

真正有趣的一点是,微软有一个 KB 文章关于这个,并且在文章中他们说这个错误是“按设计”。

历史

版本 1.0 - 2004/8/27。

© . All rights reserved.