ASP.NET

DropDownList, RadioButtonList and CheckBoxList in ASP.NET: binding, reading and validating

ASP.NET · · Published 2026-11-29

The DropDownList, RadioButtonList and CheckBoxList share one model: a collection of ListItem objects, each with a text the user reads and a value the code uses. They are filled the same way and read the same way on the server, but they render very different HTML, which is why reading and validating them in the browser differs. This guide covers the whole cycle for all three: filling them from a database, enriching the items, reading the choice in JavaScript or jQuery, and validating it with the declarative validators first and script only where the validators stop.

Which validator for which control

ControlRenders as"Something must be chosen"Script needed for
DropDownListOne <select>RequiredFieldValidator with InitialValueRules that combine fields
RadioButtonListA group of radio inputsRequiredFieldValidatorConditional rules
CheckBoxListSeveral check boxesCustomValidator (client and server)Always ("at least one", "at most N")

Binding a DropDownList to SQL Server

Every list starts empty. Filling it correctly, once, avoids half of the questions that follow.

Filling a drop-down list from a database table is one of the first things every Web Forms developer writes. Three properties do the work: DataSource, DataTextField and DataValueField. The details that make it correct are the placeholder item, binding only once, and validating the choice.

Markup

<asp:Label runat="server" AssociatedControlID="ddlCategory" Text="Category" />
<asp:DropDownList ID="ddlCategory" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="" Text="-- choose a category --" />
</asp:DropDownList>
<asp:RequiredFieldValidator runat="server" ControlToValidate="ddlCategory" InitialValue=""
    ErrorMessage="Please choose a category." Display="Dynamic" />
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click" />

AppendDataBoundItems="true" keeps the static placeholder and appends the database rows after it. The validator's InitialValue="" makes the placeholder count as "nothing chosen".

Code-behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindCategories();
    }
}

private void BindCategories()
{
    string cs = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
    using (var con = new SqlConnection(cs))
    using (var cmd = new SqlCommand("SELECT CategoryId, Name FROM dbo.Categories WHERE Active = 1 ORDER BY Name", con))
    {
        con.Open();
        using (SqlDataReader r = cmd.ExecuteReader())
        {
            ddlCategory.DataSource = r;
            ddlCategory.DataTextField = "Name";        // what the user sees
            ddlCategory.DataValueField = "CategoryId"; // what is posted
            ddlCategory.DataBind();
        }
    }
}

protected void btnNext_Click(object sender, EventArgs e)
{
    if (!IsValid) return;
    int categoryId = int.Parse(ddlCategory.SelectedValue);
    string categoryName = ddlCategory.SelectedItem.Text;
    // ...
}

Binding inside if (!IsPostBack) matters: the list keeps its items across postbacks through view state, and rebinding in every Page_Load would reset the user's selection before btnNext_Click reads it. If you must rebind (for example after adding a category), call ddlCategory.Items.Clear() first and re-add the placeholder, or the items accumulate because of AppendDataBoundItems.

Binding to a reader works because the list enumerates it once during DataBind, while the connection is still open.

Variations

Common mistakes

Tooltips on DropDownList items

Long item texts can be explained with a title on each option, with one view-state surprise.

When item texts are truncated, or need an explanation, a title attribute on each <option> shows the full text on hover in desktop browsers. In Web Forms you add it through ListItem.Attributes. There is one surprise: those attributes are not saved in view state.

Adding titles after binding

<asp:DropDownList ID="ddlPlan" runat="server" OnDataBound="ddlPlan_DataBound" ToolTip="Choose a support plan" />
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlPlan.DataSource = PlanRepository.All();   // Id, Name, Description
        ddlPlan.DataTextField = "Name";
        ddlPlan.DataValueField = "Id";
        ddlPlan.DataBind();
    }
}

protected void ddlPlan_DataBound(object sender, EventArgs e)
{
    AddTitles();
}

private void AddTitles()
{
    var descriptions = PlanRepository.All().ToDictionary(p => p.Id.ToString(), p => p.Description);
    foreach (ListItem item in ddlPlan.Items)
    {
        if (descriptions.TryGetValue(item.Value, out string d))
            item.Attributes["title"] = d;  // rendered as <option title="..."> and HTML-encoded
    }
}

The control's own ToolTip property sets a title on the <select> itself, shown when the closed list is hovered.

The postback problem

ListItem stores its text, value, selection and enabled state in view state, but not its Attributes. After a postback, the items are restored without titles. Re-apply them on every request, after view state has been loaded:

protected void Page_PreRender(object sender, EventArgs e)
{
    AddTitles(); // runs on the first request and on every postback
}

With PreRender in place, the DataBound handler above becomes optional. Cache the descriptions if loading them is expensive.

Browser behaviour

So treat the tooltip as a convenience. If users need the description to choose correctly, show it next to the list for the selected item:

var ddl = document.getElementById("<%= ddlPlan.ClientID %>");
var help = document.getElementById("planHelp");
function showHelp() { var o = ddl.options[ddl.selectedIndex]; help.textContent = o ? o.title : ""; }
ddl.addEventListener("change", showHelp); showHelp();

Binding the list in the first place is covered in Bind a DropDownList from SQL Server.

Common mistakes

Reading the selected value or text in the browser

On the client, the list is a plain <select> and the selection is one property away.

A DropDownList is a <select> in the browser. The selected item has two pieces of information: its value (the value attribute, usually an id) and its text (what the user reads). Both are one property away, in plain JavaScript or in jQuery.

JavaScript and jQuery code reading the selected value and text of a DropDownList
Reading the value and the text of the selected item.

The control

<asp:DropDownList ID="ddlSize" runat="server">
    <asp:ListItem Value="" Text="-- size --" />
    <asp:ListItem Value="S" Text="Small" />
    <asp:ListItem Value="M" Text="Medium" />
    <asp:ListItem Value="L" Text="Large" />
</asp:DropDownList>
<span id="sizeInfo"></span>

Plain JavaScript

var ddl = document.getElementById("<%= ddlSize.ClientID %>");

var value = ddl.value;                                   // "M"
var text = ddl.selectedIndex >= 0
    ? ddl.options[ddl.selectedIndex].text                // "Medium"
    : "";
// In current browsers, also: ddl.selectedOptions[0].text

.text returns the option's text with white space collapsed; .textContent returns it raw. selectedIndex is -1 only when nothing is selected, which cannot happen in a normal single-selection list with at least one option, but the check costs nothing.

jQuery

var $ddl = $("#<%= ddlSize.ClientID %>");

var value = $ddl.val();                         // "M"
var text = $ddl.find("option:selected").text(); // "Medium"

Use $ddl.find("option:selected") rather than a global $("option:selected"), which would collect the selected options of every list on the page.

Reacting to a change

// plain JavaScript
ddl.addEventListener("change", function () {
  var info = document.getElementById("sizeInfo");
  info.textContent = this.value === ""
      ? "Please choose a size."
      : "You chose " + this.options[this.selectedIndex].text + " (" + this.value + ").";
});

// jQuery
$ddl.on("change", function () {
  var $opt = $(this).find("option:selected");
  $("#sizeInfo").text($opt.val() ? "You chose " + $opt.text() : "Please choose a size.");
});

textContent and jQuery's .text() insert the option text as text, never as HTML, which keeps the page safe even if option labels come from user data.

The placeholder item

A first item with an empty value such as "-- size --" is a common way to force a choice. Test the value, not the index or the text, to know whether the user picked something. On the server, a RequiredFieldValidator with InitialValue="" enforces the same rule, as shown in Validate a DropDownList.

Multi-select ListBox

An asp:ListBox with SelectionMode="Multiple" renders <select multiple>. Collect every selected option:

var lb = document.getElementById("<%= lbTags.ClientID %>");
var values = Array.from(lb.selectedOptions, function (o) { return o.value; });

// jQuery: val() returns an array for multiple selects (an empty array when nothing is selected, jQuery 3+)
var values2 = $("#<%= lbTags.ClientID %>").val();

On the server

The same information is available after a postback through ddlSize.SelectedValue and ddlSize.SelectedItem.Text. Do not rely on values read by script and copied into hidden fields: read the control itself and validate the value. Setting the selection from script is the subject of Set a DropDownList's selected value or text.

Validating a DropDownList

Reading the choice leads to checking it: here the placeholder item is the enemy.

Lists usually start with a placeholder such as "-- choose --". Validation means checking that the selected item is not that placeholder. ASP.NET has a declarative way to do it with no script at all; a custom function is only needed for extra rules.

1. RequiredFieldValidator with InitialValue

<asp:DropDownList ID="ddlCountry" runat="server">
    <asp:ListItem Value="0" Text="-- choose a country --" />
    <asp:ListItem Value="DE" Text="Germany" />
    <asp:ListItem Value="IT" Text="Italy" />
    <asp:ListItem Value="NZ" Text="New Zealand" />
</asp:DropDownList>
<asp:RequiredFieldValidator runat="server" ControlToValidate="ddlCountry" InitialValue="0"
    ErrorMessage="Please choose a country." Display="Dynamic" />

InitialValue tells the validator which value means "nothing selected". If the placeholder's value is an empty string, omit InitialValue (its default is empty). The validator runs in the browser and again on the server.

2. CustomValidator for extra rules

Suppose shipping to some countries requires a postcode. A custom validator can combine fields:

<asp:TextBox ID="txtPostcode" runat="server" />
<asp:CustomValidator ID="cvPostcode" runat="server" Display="Dynamic"
    ErrorMessage="A postcode is required for this country."
    ClientValidationFunction="validatePostcode" OnServerValidate="cvPostcode_ServerValidate"
    ValidateEmptyText="true" ControlToValidate="txtPostcode" />

Plain JavaScript:

function validatePostcode(source, args) {
  var country = document.getElementById("<%= ddlCountry.ClientID %>").value;
  var needsPostcode = ["DE", "IT"].indexOf(country) >= 0;
  args.IsValid = !needsPostcode || args.Value.trim() !== "";
}

jQuery version of the same function:

function validatePostcode(source, args) {
  var country = $("#<%= ddlCountry.ClientID %>").val();
  args.IsValid = $.inArray(country, ["DE", "IT"]) < 0 || $.trim(args.Value) !== "";
}

With ControlToValidate set, args.Value holds the text box value. ValidateEmptyText="true" is essential here: by default, custom validators skip empty fields, which is exactly the case we want to catch.

protected void cvPostcode_ServerValidate(object source, ServerValidateEventArgs args)
{
    bool needsPostcode = ddlCountry.SelectedValue == "DE" || ddlCountry.SelectedValue == "IT";
    args.IsValid = !needsPostcode || !string.IsNullOrWhiteSpace(args.Value);
}

3. Checking without validators

In a page that does not use validation controls, a quick script check before submitting:

document.getElementById("<%= btnNext.ClientID %>").addEventListener("click", function (e) {
  var ddl = document.getElementById("<%= ddlCountry.ClientID %>");
  if (ddl.value === "0") {
    e.preventDefault();
    alert("Please choose a country.");
    ddl.focus();
  }
});

…and the server must repeat it: if (ddlCountry.SelectedValue == "0") { /* reject */ }.

Remember

Common mistakes

Validating a RadioButtonList

Radio buttons have one value or none, which makes them simpler to validate than they look.

Unlike the CheckBoxList, a RadioButtonList has a single value (the selected item, or nothing), so a RequiredFieldValidator can validate it directly. Script is only needed for conditional rules or for checks outside the validation framework.

RadioButtonList markup with a RequiredFieldValidator
A RequiredFieldValidator attached to a RadioButtonList.

The simple case

<fieldset>
    <legend>Delivery</legend>
    <asp:RadioButtonList ID="rblDelivery" runat="server" RepeatLayout="Flow">
        <asp:ListItem Value="std">Standard (3–5 days)</asp:ListItem>
        <asp:ListItem Value="exp">Express (next day)</asp:ListItem>
        <asp:ListItem Value="pick">Pick up in store</asp:ListItem>
    </asp:RadioButtonList>
</fieldset>
<asp:RequiredFieldValidator runat="server" ControlToValidate="rblDelivery"
    ErrorMessage="Choose a delivery method." Display="Dynamic" />

Do not mark an item as Selected by default if you want to force a conscious choice. The list renders radio inputs sharing one name (for example ctl00$MainContent$rblDelivery) and ids …rblDelivery_0, _1, _2.

Reading the choice in plain JavaScript

function selectedDelivery() {
  var list = document.getElementById("<%= rblDelivery.ClientID %>");
  var checked = list.querySelector("input[type=radio]:checked");
  return checked ? checked.value : null;
}

The same with jQuery

function selectedDelivery() {
  return $("#<%= rblDelivery.ClientID %> input:radio:checked").val() || null;
}

Both return the item's Value ("std", "exp", "pick"), or null if nothing is selected.

A conditional rule with a CustomValidator

Store pick-up requires choosing a store from a list:

<asp:DropDownList ID="ddlStore" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="" Text="-- store --" />
</asp:DropDownList>
<asp:CustomValidator runat="server" ErrorMessage="Choose a store for pick-up." Display="Dynamic"
    ClientValidationFunction="validateStore" OnServerValidate="cvStore_ServerValidate" />
<script>
  function validateStore(source, args) {
    args.IsValid = selectedDelivery() !== "pick" ||
                   document.getElementById("<%= ddlStore.ClientID %>").value !== "";
  }
</script>
protected void cvStore_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = rblDelivery.SelectedValue != "pick" || ddlStore.SelectedValue != "";
}

Showing or hiding the store list when the delivery choice changes is a nice touch: listen for change on the radio inputs and toggle the list's container. Hidden or not, the server rule stays.

Server side

rblDelivery.SelectedValue is an empty string when nothing is selected, and SelectedItem is null. Check Page.IsValid in the button handler before using them.

Related: Validate a CheckBoxList, Validate a DropDownList.

Common mistakes

Validating a CheckBoxList

Check boxes are the one case where a CustomValidator is always needed.

A RequiredFieldValidator cannot target a CheckBoxList: the list renders many inputs, not one value. The standard answer is a CustomValidator with a client-side function and the same rule on the server. The client function is a few lines in plain JavaScript or jQuery.

Markup

<asp:CheckBoxList ID="cblTopics" runat="server" RepeatLayout="Flow" CssClass="topics">
    <asp:ListItem Value="web">Web Forms</asp:ListItem>
    <asp:ListItem Value="sql">SQL Server</asp:ListItem>
    <asp:ListItem Value="js">JavaScript</asp:ListItem>
    <asp:ListItem Value="css">CSS</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="cvTopics" runat="server" Display="Dynamic"
    ErrorMessage="Choose between one and three topics."
    ClientValidationFunction="validateTopics"
    OnServerValidate="cvTopics_ServerValidate" />
<asp:Button ID="btnSubscribe" runat="server" Text="Subscribe" OnClick="btnSubscribe_Click" />

Leave ControlToValidate empty: a CustomValidator without it still runs, and it would not accept a CheckBoxList as target anyway. The list renders one <input type="checkbox"> per item, with ids such as cblTopics_0, cblTopics_1, inside a container whose id is the list's ClientID.

Client function: plain JavaScript

<script>
  function validateTopics(source, args) {
    var list = document.getElementById("<%= cblTopics.ClientID %>");
    var checked = list.querySelectorAll("input[type=checkbox]:checked").length;
    args.IsValid = checked >= 1 && checked <= 3;
  }
</script>

ASP.NET calls the function with the validator (source) and an object whose IsValid you set. The check runs when the button is clicked, before the postback.

Client function: jQuery

function validateTopics(source, args) {
  var checked = $("#<%= cblTopics.ClientID %> input:checkbox:checked").length;
  args.IsValid = checked >= 1 && checked <= 3;
}

// Optional: re-validate as soon as a box changes, so the message disappears immediately
$(function () {
  $("#<%= cblTopics.ClientID %>").on("change", "input", function () {
    ValidatorValidate(document.getElementById("<%= cvTopics.ClientID %>"));
  });
});

ValidatorValidate is part of ASP.NET's validation script and re-runs a single validator.

Server-side check (always)

protected void cvTopics_ServerValidate(object source, ServerValidateEventArgs args)
{
    int count = cblTopics.Items.Cast<ListItem>().Count(i => i.Selected);
    args.IsValid = count >= 1 && count <= 3;
}

protected void btnSubscribe_Click(object sender, EventArgs e)
{
    if (!IsValid) return;   // validators have run; never skip this
    var topics = cblTopics.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToList();
    Subscribe(topics);
}

Client validation is for convenience; a user can disable it or post directly. Page.IsValid covers both the server-side handler and the other validators on the page.

Accessibility

With RepeatLayout="Flow" the items are rendered in spans; the default Table layout uses a table. In both cases, wrap the list in a <fieldset> with a <legend> ("Topics") so screen readers announce the group name with each box.

Same technique for other list controls: RadioButtonList and DropDownList.

Common mistakes

Setting a selection from script, rather than reading it, has its own detailed article: set a DropDownList selection with JavaScript or jQuery. Lists that depend on each other are covered in cascading country, state and city drop-downs.

Checklist

Sources