动态添加标签看起来像标签

时间:2016-01-27 12:25:56

标签: c# css asp.net code-behind

我想做的是与SO在主页上做的类似:

enter image description here

所以,我所做的就是添加这段代码:

C#Code-Behind:

    protected void LoadInterests()
    {

        //Fill Interests based on table values
        string strSQL2 = "SELECT UM.MatchValue, DD.DDLValue FROM tmpUsermatch UM ";
        strSQL2 = strSQL2 + "INNER JOIN (SELECT StoredValue, DDLValue FROM tmpDropdowns WHERE ddlName = 'ddlInterests') DD ";
        strSQL2 = strSQL2 + "ON UM.MatchValue = DD.StoredValue ";
        strSQL2 = strSQL2 + "WHERE MatchField = 'MatchInterests'  AND UserID = '" + lblUserID.Text + "'";
        using (var con = new SqlConnection(strCon1))
        using (var adapter2 = new SqlDataAdapter(strSQL2, con))
        {
            DataTable dt2 = new DataTable();
            adapter2.Fill(dt2);
            foreach (DataRow row in dt2.Rows)
            {
                Label dynamicLabel = new Label();
                dynamicLabel.ID = "lbl" + row["DDLValue"].ToString();
                dynamicLabel.Text = row["DDLValue"].ToString();
                dynamicLabel.CssClass = "lbl.interests";
                div1.Controls.Add(dynamicLabel);
            }
        }
    }

asp.net:

    <div>
        <asp:Panel ID="Panel1" runat="server" Height="100px" ScrollBars="Vertical" Style="float: left; margin-left: 1px; background-color:#f5f5f5" Width="807px" BorderColor="LightSteelBlue" BorderStyle="Solid" BorderWidth="1px">
            <div id="div1" runat="server" class="clear" style="width:820px; border-width:1px; margin-left:20px"></div>
        </asp:Panel>
    </div>

CSS:

lbl.interests
{
    background-color: #465c71;    
/*    background-color: white;    */
    border: 1px #4e667d solid;  
    color: white;
    display: block;
    line-height: 1.35em;
    padding: 4px 20px;
    text-decoration: none;
    white-space: nowrap;
}

最终结果仍是这样:

enter image description here

当我希望它看起来像这样:

enter image description here

关于我哪里出错的任何想法?

1 个答案:

答案 0 :(得分:1)

更改行

dynamicLabel.CssClass = "lbl.interests";  

dynamicLabel.CssClass = "lbl interests";      

将CSS选择器更改为

.lbl.interests

请记住.仅用于在CSS中选择类名,它不会出现在HTML中,如果您在css中仅指定名称lbl,那么您指的是HTML中的TAG是根据HTML的无效标记,也与代码匹配。

我的建议是首先编写纯HTML和CSS并确认您的布局按预期工作,然后使用C#/ ASP.Net生成HTML

有关CSS选择器的帮助,请参阅以下链接 W3Schools - CSS Selectors