ASP.NET (C#) DropDownList

last edited on: 22-Jan-2018; tagged: c#

The ASP DropDownList control is used to create a single selection drop-down list control. We can control the appearance of the DropDownList control by setting the BorderColor, BorderStyle, and BorderWidth properties. CssClass we can use this property to set CSS Class name for this.

To add items that appear in the DropDownList control, we can use ListItem element for each entry between the opening and closing tags of the DropDownList control.

<asp:DropDownList id="ddl1" runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>

The DropDownList control support data binding. The data source can be a DataSet, DataTable. Example:

DropDownList1.DataSource = DataTable/DataSet;  
DropDownList1.DataTextField = "Full Name";
DropDownList1.DataValueField = "StudentId";
DropDownList1.Items.Insert(0, new ListItem("--Select--", "0"));  // Adding the first Item on the DropDownList and that will selected

Add Item to DropDownList:

ListItem listMonth = new ListItem();
listMonth.Text = "February";
listMonth.Value = "2";

Get Selected Value or Text:

String myValue = DropDownList1.SelectedItem.Value;
String myValue = DropDownList1.SelectedItem.Text;

Get Item by Index:

Label1.Text = DropDownList1.Items[2].Text;

Modify Value or Text of an Item in DropDownList:

DropDownList1.Items[2].Text="My Text";

Remove Items from DropDownList:

Remove Single Item from DropDownList

// Way 1 By Value
ListItem removeItem = DropDownList1.Items.FindByValue("2");
// Way 2 By Text
ListItem removeItem = DropDownList1.Items.FindByText("February");
// Way 3 By Index

Remove All Items from DropDownList:




ASP.NET (C#) Sending Bulk Email

tagged: c#,smtp

C# DataTable

tagged: c#,datatable

C# Sending Email with SSL 465 or 587

tagged: c#,smtp