c# - 从数据库动态绑定(bind) css 类到 asp.net c# 中的 div 标签

标签 c# html css asp.net

我在 ListView 中动态创建标签,标签放置在 div 标签内,我希望为每个标签更改标签的 cssclass。我正在从数据库中动态获取标签的名称,并且该数据库包含每个名称的 cssclasses。那么如何将 cssclass 动态绑定(bind)到 div 标签呢?以下是代码

<asp:ListView ID="ListView1" runat="server">
    <ItemTemplate>
        <div class="sidebar-links">
            <div class="link-blue">
        <a href="#"><i class="fa fa-archive"></i><asp:Label ID="Label1" runat="server" Text='<% #Bind ("mdl_name") %>' ></asp:Label></a>

            </div>
            </div>
    </ItemTemplate>
    </asp:ListView>

这是代码隐藏

DataTable dt1 = (DataTable)Session["SessionUserInfo"];

String type = dt1.Rows[0]["user_id"].ToString();
SqlConnection conn = new SqlConnection("Data Source=BABA; Database=afaqandco; Integrated Security=true");
SqlCommand cmd = new SqlCommand("SELECT ma.*, m.* FROM tblmdluserassociation AS ma INNER JOIN tbl_module AS m ON ma.mdl_id=m.mdl_id WHERE ma.user_id='"+type+"'", conn);

        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;

        DataTable dt = new DataTable();
        da.Fill(dt);

        ListView1.DataSource = dt;
        ListView1.DataBind();

最佳答案

您应该将 ItemDataBound 方法添加到 ListView ,然后在代码后面创建它,如下所示:

        <asp:ListView ID="ListView1" runat="server" ItemPlaceholderID="itemplaceholder" OnItemDataBound="ListViewMenu_ItemDataBound">
        <LayoutTemplate>
            <asp:PlaceHolder ID="itemplaceholder" runat="server" />
        </LayoutTemplate>
        <ItemTemplate>
            <div class="sidebar-links">
                <div id="MYDIV" runat="server">
                    <a href="#"><i class="fa fa-archive"></i>
                        <asp:Label ID="Label1" runat="server" Text='<% #Bind("mdl_name") %>'></asp:Label></a>

                </div>
            </div>
        </ItemTemplate>
    </asp:ListView>

代码隐藏

    protected void ListViewMenu_ItemDataBound(object sender, ListViewItemEventArgs e)
{

    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        ListViewDataItem listViewDataItem = e.Item as ListViewDataItem;
        HtmlGenericControl divControl = e.Item.FindControl("MYDIV") as HtmlGenericControl;
        DataRowView dataRow = ((DataRowView)listViewDataItem.DataItem);
        divControl.Attributes.Add("class", dataRow["CLASS"].ToString());
    }

}

关于c# - 从数据库动态绑定(bind) css 类到 asp.net c# 中的 div 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336026/

相关文章:

c# - 我可以重用通过 "using"语句释放的对象吗

c# - 当子实体有多个路径时,如何生成对象?

javascript - 从 Web 服务器的 HTML 资源中播放 FLAC

php - DataTables 调整大小的响应问题

html - 导入 html 字体及其样式变体?

c# - Math.Log 与几何平均数的乘法复杂度哪个更好?

c# - 在带有模拟器的 Xamarin.iOS 中使用 Azure AD B2C - 钥匙串(keychain)问题(团队 ID 为空)

html - 固定容器中的侧面导航

html - 使用::之前在图像上添加叠加层

javascript - 页面上显示的 Div,除非按下按钮,否则不应显示