Bind the 'style' property of a DropDownLis

2019-08-15 07:59发布

问题:

I have following code inside my ListView template.

  <asp:DropDownList runat="server" ID="myDropDown" Width="60px"
     SelectedValue='<%# Eval("SelectedValue") %>' 
     DataSource='<%# Eval("DropDownList") %>'
     style='display:<%# (bool)Eval("ShowDropDown") ? "block" : "none" %>;' >
  </asp:DropDownList>

The idea is that it will generate the html, but hidden so I can show the client-side.

However, the html generated looks like this:

<select id="myDropDown" 
   style="width:60px;display:<%# (bool)Eval("ShowDropDown") ? "block" : "none" %>;">

I don't understand why it does this. Is there a way to do this (without using classes)?

回答1:

You can add a ListView ItemDataBound Event and then add the style attribute for dropdownlist in each row. Sample Code:

protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
                DropDownList myDropDown = (DropDownLiast)e.Item.FindControl("myDropDown");

                System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
                myDropDown.Style["display"] = ((bool)rowView["ShowDropDown"])?"block":"none";
        }
}