Anand Kumar M Anand Kumar M - 1 month ago 8
ASP.NET (C#) Question

Dropdownlist validation in Asp.net Using Required field validator

I have Dropdownlist whose value field and text field are bind at runtime.
it has

--select--
as first item with a value of
0

and the rest of the values are bind at runtime.

I have given validaton group for both the control and the validator as
"g1"

and
Intialvalue=0


But still the page is posting back even if I select
--select--
option.

<asp:DropDownList AutoPostBack="true" CssClass="dropdown" ValidationGroup="g1"
ID="ddlReportType" runat="server"
OnSelectedIndexChanged="ddlReportType_SelectedIndexChanged"></asp:DropDownList>

<asp:RequiredFieldValidator ControlToValidate="ddlReportType" ID="RequiredFieldValidator1"
ValidationGroup="g1" CssClass="errormesg" ErrorMessage="Please select a type"
InitialValue="0" runat="server" Display="Dynamic">
</asp:RequiredFieldValidator>


And code Behind to Bind the Dropdown

ddlReportType.Items.Clear();
ddlReportType.DataSource = dt.Tables[0];
ddlReportType.DataTextField = "ReportType";
ddlReportType.DataValueField = "ReportTypeID";
ddlReportType.DataBind();
ddlReportType.Items.Insert(0, new ListItem("--Select--", "0"));
//ddlReportType.Items[0].Value = "0";
ddlReportType.SelectedIndex = 0;

Answer
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic" 
    ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
    Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>