Since you're using form-control
CSS class, I'm sure that you're using Bootstrap CSS.
In Bootstrap, it is possible to implement multi-line options using data-content
attribute for select
element.
Note: For 2 first choices available below, ensure any long string value you want to show in data-content
have <br />
tag inserted between them (see this example fiddle). The tag can be inserted by using String.Insert
(suggested using additional property that stores wrapped value in address
class):
foreach (var addr in addressAll)
{
if (addr.address.Length >= [position_index])
{
// new property to store wrapped values to be displayed in data-content attribute
addr.longAddress = addr.address.Insert([position_index], "<br />");
}
}
1) To implement the custom attribute with asp:DropDownList
server control, add it manually in code-behind after data binding. Here is the code-behind part:
protected void Page_Load(object sender, EventArgs e)
{
List<address> addressAll = ... //get table data from SQL that has been returned as a list
addressDdl.DataSource = addressAll;
addressDdl.DataTextField = "address";
addressDdl.DataValueField = "addressID";
addressDdl.DataBind();
addressDdl.Items.Insert(0,"--Select--");
// before transform the list into array, use foreach loop provided above
var arr = addressAll.ToArray();
// note: zero-index skipped here
for (int i = 1; i <= addressDdl.Items.Count; i++)
{
// add data-content attribute for select options
addressDdl.Items[i].Attributes.Add("data-content", arr[i - 1].longAddress.ToString());
}
}
2) As an alternative, a Repeater
may be used to replace DropDownList
with plain select
element, but with ItemTemplate
to set option attributes:
ASPX
<asp:Repeater ID="rptDeliveryAddress" runat="server">
<HeaderTemplate>
<select id="addressDdl">
<option value="">--Select--</option>
</HeaderTemplate>
<ItemTemplate>
<option data-content="<%# DataBinder.Eval(Container.DataItem, "[longAddress]") %>" value="<%# DataBinder.Eval(Container.DataItem, "[address]") %>"><%# DataBinder.Eval(Container.DataItem, "[address]") %></option>
</ItemTemplate>
<FooterTemplate>
</select>
</FooterTemplate>
</asp:Repeater>
3) Another way I know to use multi-line dropdown is manipulating width in CSS selector together with selectPicker
:
ASPX
<asp:DropDownList ID="addressDdl" runat="server" CssClass="form-control selectpicker large-bootstrap-select" ... />
CSS
/* CSS Class */
.bs-container.large-bootstrap-select {
.dropdown-menu {
width: 100px; /* set this attribute with desired size in pixels */
li a span.text {
word-wrap: break-word;
white-space: normal;
}
}
}
JS
$('#<%= addressDdl.ClientID %>').selectpicker();
References:
How to add a data-attribute to a dropdown menu with C#
Is it possible to have multi-line options?
` between texts. – Tetsuya Yamamoto Jul 27 '17 at 07:25