在Datalist里面放一个绑定控件
<asp:Label ID="Label2" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "公司名称")%'></asp:Label>
我想在页面代码块里放一段代码,根据不同的公司名称显示不同的颜色

<%string a=((Label)DataList1.Items[i].FindControl("Label2")).Text;                                                                                                                     if (a.Equals("免费会员")) { Response.Write("<font color='#DB7093'>"); }
                                                                                                                     else  { Response.Write("<font color='#CD2626'>"); }                                                                                                               %>
但这样做又不能获得i,请问怎样直接获得绑定Label的值呢???

解决方案 »

  1.   


    <asp:Label ID="Label1" runat="server" Text='<%# Eval("用户名","[{0}]") %>' 
          ForeColor='<%# this.NameColor((string)Eval("分类")) %>' />
    这里绑定了“用户名、分类”两个字段。   protected System.Drawing.Color NameColor(string name) 
      { 
          if (name == "特别关注") 
              return System.Drawing.Color.Red; 
          else 
              return System.Drawing.Color.DarkBlue; 
      } 
    相似,你看着改改吧
      

  2.   

    <asp:DataList ID="DataList1" runat="server">
        <ItemTemplate>
        <asp:Label ID="Label2" runat="server" Text=' <%# DataBinder.Eval(Container.DataItem, "公司名称") %>' ForeColor='<%# DataBinder.Eval(Container.DataItem, "公司名称").ToString() == "免费会员" ? System.Drawing.Color.Red :System.Drawing.Color.Black %>'> </asp:Label> 
        </ItemTemplate>
    </asp:DataList>
      

  3.   

    1楼的可以protected string GetColor(string name) 

    switch (name) 
    case "1":
    return "#ff0000"; 
    break;
    case "2":
    return "#ffff00"; 
    break;
    case "3":
    return "#cccccc"; 
    break;
    default:
    return "#000000"; 
    break;
      

  4.   

     属性中加事件OnItemDataBound="Datalist_RowDataBound"
     protected void Datalist_RowDataBound(object s, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Label rb = (Label)e.Item.FindControl("comLabel");
                if (rb.Text == "公司名")
                 rb.BackColor=System.Drawing.Color.DarkBlue;
                else if( rb.Text == "另一公司名")
                     rb.BackColor=System.Drawing.Color.Red;
            }    }