代码之家  ›  专栏  ›  技术社区  ›  LesterDove

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

  •  13
  • LesterDove  · 技术社区  · 14 年前

    <asp:DropDownList ID="DropDownList1" runat="server" 
    AutoPostBack="True" DataSourceID="objDataSource1" 
    DataTextField="FieldName" DataValueField="FieldID" />
    

    从中接收数据的数据表 DataTextField DataValueField 值还返回有关记录的其他有趣信息。说 Active = Y/N

    我想做的是根据数据源结果中的活动字段设置DropDownList项的background color属性。此外,当DropDownList绑定到数据时,我想“在同一过程中”这样做。所以我猜这必须发生在OnDataBound。

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

    1. 稍后我可以返回并循环查看DropDownList项。但这会涉及到嵌入循环和重新访问数据表行,而且效率似乎很低

       int row;
       for (row = 0; row < DropDownList1.Items.Count - 1; row++)
       {
          [[if this row = that data row]]
           DropDownList1.Items[row].[[DoStuffHere, etc.]]
       }
      
    2. OnRowDataBound 事件,通过访问 GridViewRowEventArg OnDropDownListItemBound 事件,可以说。

    2 回复  |  直到 9 年前
        1
  •  25
  •   Matthew Jones    14 年前

    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");
        }
    }
    
        2
  •  1
  •   Salah Salem    7 年前

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