下拉列表必填字段验证器

时间:2014-05-21 05:50:56

标签: c#

我有一个下拉菜单,它会自动从数据库中填充值。为此,我在前端使用以下代码:

public void des_fill()
{
     string q = "SELECT -1 AS pick_det_id,'' AS pick_det_name UNION select pick_det_id,pick_det_name from tbl_pick_list_detail where pick_hdr_id=(select pick_hdr_id from tbl_pick_list_header where pick_hdr_name='Designation')";
     isopen();
     conn.Open();
     code cd = new code();
     SqlDataReader dr = cd.Reader(q);
     ddlDes.DataSource = dr;
     ddlDes.DataValueField = "pick_det_id";
     ddlDes.DataTextField = "pick_det_name";
     ddlDes.DataBind();
     conn.Close();
}

我正在使用它:

SELECT -1 AS pick_det_id,'' AS pick_det_name UNION

表示开始下拉列值为空。

但是通过使用此必填字段不起作用。当我单击“保存”按钮时,它不会要求输入必填字段,并保存记录。

2 个答案:

答案 0 :(得分:1)

@thiru for required field validator place InitialValue = 0 <asp:RequiredFieldValidator ID="RFVQualification" runat="server" ControlToValidate="ddlQualification" CssClass="requiredfieldvalidatorstyle" Display="Static" ErrorMessage="*" InitialValue="0"></asp:RequiredFieldValidator>

这里InitalValue指的是DropDown的起始索引

答案 1 :(得分:0)

执行以下操作,使用ValidationGroup添加文本框,并在c#级别上验证该组,如下所示:

for Textbox

<asp:TextBox ID="FirstName" runat="server" 
        AutoPostBack="false" ValidationGroup="UserInfor"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
     runat="server" ControlToValidate="FirstName"    
     ErrorMessage="First Name is requried" ForeColor="Red"
     ValidationGroup="UserInfor">    </asp:RequiredFieldValidator>

对于下拉列表,您应该添加值InitialValue,如下所示:

<asp:DropDownList runat="server" id="ddAge"  ValidationGroup="UserInfor">
<asp:ListItem Value="-1" text="Select a Value">
<asp:ListItem Value="15" text="15 years">
<asp:ListItem Value="20" text="20 years">
<asp:ListItem Value="30" text="30 years">
</asp:DropDownList>


<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
     runat="server" ControlToValidate="ddAge"   InitialValue="-1"  
     ErrorMessage="Age requried" ForeColor="Red"
     ValidationGroup="UserInfor">    </asp:RequiredFieldValidator>

然后在c#级别添加以下内容:

Validate("UserInfor");
    if (Page.IsValid) {
                lblOutput.Text = "Required field is filled!";
             }
             else {
                lblOutput.Text = "Required field is empty!";
             }