如何在onDataBinding事件期间格式化单个DropDownlist项(颜色等)

我有一个绑定到ObjectDataSource的基本DropDownList:

 

从中接收DataTextFieldDataValueField值的DataTable还返回有关记录的一些其他有趣信息。 为简单起见,说Active = Y/N

我想要做的是根据DataSource结果中的Active字段设置DropDownList项的background-color属性。 此外,我想在DropDownList与数据绑定时“在相同的传递中”执行此操作。 所以我的猜测是它必须在OnDataBound期间发生。

我已经知道/尝试的事情:

  1. 我可以稍后返回并循环访问DropDownList项。 但它将涉及嵌入循环并重新访问DataTable行,它似乎效率低下

      int row; for (row = 0; row < DropDownList1.Items.Count - 1; row++) { [[if this row = that data row]] DropDownList1.Items[row].[[DoStuffHere, etc.]] } 
  2. 我们已经使用GridView OnRowDataBound事件通过访问GridViewRowEventArg来执行OnRowDataBound 。 我似乎缺少的是一个OnDropDownListItemBound事件,可以这么说。

希望我清楚简洁。 似乎应该很容易……

在OnDataBinding期间无法执行此操作,因为数据尚未实际绑定。 你最好的镜头是(1),也就是说,使用OnDataBound并遍历项目。

 protected void DropDownList1_DataBound(object sender, EventArgs e) { foreach(ListItem myItem in DropDownList1.Items) { //Do some things to determine the color of the item //Set the item background-color like so: myItem.Attributes.Add("style","background-color:#111111"); } } 

我正在使用此代码,它与我一起正常工作:

 DropDownList1.Items(0).Attributes.CssStyle.Add("color", "Blue"); DropDownList1.Items(0).Attributes.CssStyle.Add("background-color", "#eae9e9");