我在列表视图中动态创建标签,标签放在div标签内,我希望为每个标签更改标签的cssclass。我从数据库动态获取标签的名称,该数据库包含每个名称的cssclasses。那么如何将cssclass动态绑定到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();
答案 0 :(得分:0)
您应该将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>
背后的代码
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());
}
}