Whenever we use DropDownList control, we will have the first item as "Select" or something similar to notify the user to select an item.
This can be achieved in two ways. In codebehind and in ASPX.
Through CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlRoles.DataSource = GetAllRoles();
ddlRoles.DataValueField = "RoleID";
ddlRoles.DataTextField = "Role";
ddlRoles.DataBind();
ddlRoles.Items.Insert(0, new ListItem("Select",""));
}
}
In ASPX
<asp:DropDownList ID="ddlRank" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="Select" Value=""></asp:ListItem>
</asp:DropDownList>
By setting AppendDataBoundItems property to true and specifying a default item in the markup will make the dropdownlist to have the first item as "Select". Setting this property will make sure that all items added henceforth in codebehind will be appended to the item collection.
Execute the page. You will receive an error message when you click Save without selecting a value in DropDownList control.
|