当我从数据库中检索时,如何验证下拉列表 [英] how to validate dropdownlist, when i retrived from database
问题描述
当我从databse中获取数据时,如何验证drowndownlist.
例如,下拉列表名称为City.如果用户未选择城市均值
然后我要在替代框中显示msg像(选择城市")
how to validate drowndownlist, when i retived data from databse.
for example dropdownlist name is City.if user does not select a city mean
then i want display msg like("slect a city) in alter box
推荐答案
绑定DropDownList后插入一个请选择项目:
After binding your DropDownList insert a please select item:
myDDL.Items.Insert(0, new ListItem("Please Select A City", "0"));
然后,在保存按钮的单击事件上,只需检查您的DropDownLists选定值:
Then, on your save button''s click event you just check your DropDownLists selected value:
if (myDDL.SelectedValue == "0")
{
myErrorLabel.Text = "Please Select a City";
return;
}
//Save info to database here
尝试类似的方法:
Try something like this:
<asp:requiredfieldvalidator id="rfvCity" runat="server" controltovalidate="ddlCity" display="Dynamic" enableclientscript="true" errormessage="Please Select a City" forecolor="Red" initialvalue="Select a City..." xmlns:asp="#unknown">* </asp:requiredfieldvalidator>
您需要在页面上的某处添加<asp:validationsummary id="valSummary" runat="server" forecolor="Red" xmlns:asp="#unknown" />
才能显示错误消息.
You''ll need to add <asp:validationsummary id="valSummary" runat="server" forecolor="Red" xmlns:asp="#unknown" />
somewhere on the page to display the error message.
验证此问题的3种方法
1.使用服务器端代码(C#,VB)
3 way to validate this problem
1. Using Server Side code (C#, VB)
if(dropdownList1.SelectedValue=="")
{
lblMessage.Text="Please Select Your City.";
return;
}
2.使用RequiredFieldValidator
2. Using RequiredFieldValidator
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="Male"></asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Please Select City" ControlToValidate="DropDownList1"
ForeColor="Red"></asp:RequiredFieldValidator>
3.使用JavaScript
3. Using JavaScript
<script type="text/javascript">
function CheckDropDownList() {
if (document.getElementById('DropDownList1').selectedIndex = "0")
alert('Please Select City');
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="CheckDropDownList()" />
了解验证控制,请访问
http://msdn.microsoft.com/en-us/library/aa479013.aspx [ ^ ]
谢谢
learn about validation control please visit
http://msdn.microsoft.com/en-us/library/aa479013.aspx[^]
Thanks
这篇关于当我从数据库中检索时,如何验证下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!