[英]bind css class dynamically from database to div tag in asp.net c#
i am creating labels dynamically in list view, the labels are placed inside the div tag and i want the cssclass of the label to be changed for each label. 我在列表视图中动态创建标签,将标签放置在div标签内,并且我希望为每个标签更改标签的cssclass。 i am getting names of the label dynamically from database and that database contains cssclasses for each name. 我正在从数据库中动态获取标签的名称,并且该数据库包含每个名称的cssclasses。 so how can i bind the cssclass dynamically to the div tag? 那么我如何将cssclass动态绑定到div标签呢? following is the code 以下是代码
<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>
This is the codebehind 这是背后的代码
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();
You should add ItemDataBound method to the list view and then create it in code behind as follows: 您应该将ItemDataBound方法添加到列表视图,然后在后面的代码中创建它,如下所示:
<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>
Code Behind 背后的代码
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.