我有两个下拉列表。
public void DrpDwn_Cuntry()
{
if (!Page.IsPostBack)
{
MySqlCommand sql_country = new MySqlCommand("SELECT DISTINCT(Country) FROM Animals", cs);
cs.Open();
MySqlDataReader ddlvalue;
ddlvalue = sql_country.ExecuteReader();
ddlcountry.DataSource = ddlvalue;
ddlcountry.DataValueField = "Country";
ddlcountry.DataTextField = "Country";
ddlcountry.DataBind();
ddlcountry.Items.Insert(0, "Choose A Sanctuary");
cs.Close();
cs.Dispose();
}
}
和
public void DrpDwn_Res()
{
if (!Page.IsPostBack)
{
MySqlCommand sql_residents = new MySqlCommand("SELECT DISTINCT(Country) FROM Animals", cs);
cs.Open();
MySqlDataReader ddlvalue_residents;
ddlvalue_residents = sql_residents.ExecuteReader();
ddlcountry_Res.DataSource = ddlvalue_residents;
ddlcountry_Res.DataValueField = "Country";
ddlcountry_Res.DataTextField = "Country";
ddlcountry_Res.DataBind();
ddlcountry_Res.Items.Insert(0, "Choose Your Country");
cs.Close();
cs.Dispose();
}
}
如果选择的两个不匹配,我希望显示一个消息框。例如,如果显示了来自第一消息框的所选国家a和来自第二消息框的国家b。我知道我要使用If-Else语句,我只是不知道该怎么写?
您可以使用DropDownList
控件的SelectedItem
属性来实现这一点。
1。获取第一个DropDownList
的SelectedItem
2.得到第二个DropDownList
的SelectedItem
3。使用Equals()
方法比较两个SelectedItem
值
4.如果项目不匹配,则使用javascript
显示一个alert
框,因为默认情况下,MessageBox
在Webforms中不可用(在Webforms中,最好使用javascript alert
),使用以下语法:
Response.Write(@"<script language='javascript'>alert('message here');</script>");
完整代码:(代码隐藏)
试试这个:
protected void Button1_Click(object sender, EventArgs e)
{
if (!ddlcountry.SelectedItem.ToString().Equals(ddlcountry_Res.SelectedItem.ToString()))
{
Response.Write(@"<script language='javascript'>alert('Items do not match.');</script>");
}
}
消息框在WinForms中可用,在WebForms中等效的是通过javascript的Alert(您需要在jQuery库中添加引用)
它来了:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js "
type="text/javascript"></script>
<script>
function compareAndAlert(){
var value1 = $('#dropDownId').val(); // get the selected value of first dropdown
var value2 = $('#dropDownId2').val(); // get the selected value of second dropdown
if (value1 != value2){
alert("The selected items do not match !"); // If the selected values are not equal display an Alert.
return false;
}
return true;
}
</script>
现在点击按钮调用这个方法
<asp:Button ID="Button1" onclientclick="javascript:if(compareAndAlert()){}else{return false;}" runat="server" OnClick="Button1_Click" Text="Adopted Pet" Height="31px" Width="150px"/>
更新:这基本上是验证,尽管Sudhakar的答案是正确的,但即使所选值不匹配,也会导致不必要的回发。这些类型的验证是最好的客户端服务。请检查更新,我已经更改了按钮的onclientclick事件中的内容