Hi
Can i attach a RequiredFieldValidator to dropdownlist in asp.net2.0?
i want to make it mandatory for the user to select an option from the
dropdownlist.
i can validate it by writing code in my code-behind file, but can i have the
dropdown validated at the client side only? Just like we validate a textbox by a requiredfieldvalidator
on client side.
Loading
Asim MirzaPosted Jun 4, 2009, 1:35 PM
I my example i am binding data from northwind database products table to my dropdownlist and finally a ListItem at the end.
<asp:DropDownList ID="DropDownList1" runat="server" CausesValidation="True" ValidationGroup="submit" DataTextField="ProductName" DataValueField="ProductID">asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1" SetFocusOnError="true" InitialValue="Select One" ValidationGroup="submit" ErrorMessage="Please Select gender">asp:RequiredFieldValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CausesValidation="true" ValidationGroup="submit" />
some code in .aspx.cs
SqlDataAdapter adp = new SqlDataAdapter("SELECT [ProductID], [ProductName] FROM [Alphabetical list of products]", ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
DataTable dtbl = new DataTable();
adp.Fill(dtbl);
DropDownList1.DataSource = dtbl;
DropDownList1.DataValueField = "ProductID";
DropDownList1.DataTextField = "ProductName";
DropDownList1.DataBind();
ListItem lst = new ListItem("Select One");
DropDownList1.Items.Insert(0, lst);
this thing will do for you.
Niradhip ChakrabortyPosted Apr 28, 2009, 6:43 AM
In your drop down list try to give the frst item as <--select value-->
Then you can use javascript to do it.
if(document.getElementById("cboSecurityQuestion").selectedIndex ==0)
{
alert("Please select the Security Question");
return false;
}
SreekanthPosted Apr 27, 2009, 5:37 AM
javascript is ok?
then try this in ur aspx page
if(document.Form1.dropdownlist1.value=="0") { alert("Select one") document.Form1.ddlregion.focus() return false; }