List Controls in ASP.NET: Part 4


In Part - 3 article of this series, we have discussed how to display records in GridView based on the selected item in DropDownList. We always use to see that it is necessary to select at-least an item in DropDownList to process the form. 

Appending Data Items

We can mix the list items that we declare in a List control and the list items that are added to the control when it is bound to a data source. This is useful when we want to display a default selection. 

For example, imagine that we are creating a form in which we want to require a user to pick an item from a List control. In this situation, we should add a default item to the List Control so we can detect whether a user has actually picked an item. We can mix declarative list items with databound list items by assigning the value true to the AppendDataBoundItems property. Let's take a look how it is created.

In above picture we have not selected any option and it is displaying the RequiredFieldValidator message.


In above picture we have selected an item from DropDownList and hence it is displaying data on form. 

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""">

<script runat="server">
    Protected Sub btnSelect_Click(ByVal sender As ObjectByVal e As EventArgs)
        lblSelectedProduct.Text = ddlProducts.SelectedItem.Text
    End Sub

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">

                Text="Selecte a Product"

        Text="Required to select" 
    <br />
        Runat="server" />

    <hr />

        Runat="server" />

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>" 
            ProviderName="<%$ ConnectionStrings:DatabaseConnectionString1.ProviderName %>" 
            SelectCommand="SELECT [ID], [NAME] FROM [PRODUCT_LIST]"></asp:SqlDataSource>


Above code page includes both a DropDownList control and a RequiredFieldValidator control. The DropDownList control includes a list item that displays the text "Select a Product." The Value property of this list item is set to the empty string. If you attempt to submit the form without selecting a list item other than the default list item, then the RequiredFieldValidator displays an error message. Notice that the DropDownList control includes an AppendDataBoundItems property which is set to the value true. If we neglect to set this property, then the databound list items overwrite any declarative list items.

Note: Continue in Next Part.


Up Next
    Ebook Download
    View all
    View all