ASP.NET - how to compare textbox value with dropdownlist items using c#.net

Asked By mani on 12-May-11 02:39 AM
hi..i have dropdownlist which contains some items..and having one textbox..here i will enter value iin textbox..if it is already available means i throw some message..otherwise i can save textbox value...
Reena Jain replied to mani on 12-May-11 02:49 AM
hi,

if you want to compare all the value of dropdownlist then use foreach loop like this

ListItem li = default(ListItem);
 
foreach ( li in mydropdownlist1.Items) {
  if (li.Value == textbox.Text) {
     
  }
}

and if you want to match selectedtext then do this

if(dropdownlist1.Text==Textbox1.Text)
{
//write the code
}
mani replied to Reena Jain on 12-May-11 02:53 AM
i used this..but some error in foreach as ....
type and identifier both required in foreach statement

foreach ( li in ddlmothertongue.Items)
{
  if (li.Value == textbox.Text)
  {
     
  }
}
dipa ahuja replied to mani on 12-May-11 03:04 AM
Hi.. One easy way is to use the CompareValidator:

<asp:DropDownList ID="DropDownList1" runat="server">
  <asp:ListItem>asp.net</asp:ListItem>
  <asp:ListItem>C#</asp:ListItem>
</asp:DropDownList>
    
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    
<asp:CompareValidator ID="CompareValidator1" runat="server" 
  ErrorMessage="Value exist in dropdown" ControlToCompare="DropDownList1" 
  ControlToValidate="TextBox1" Operator="NotEqual"></asp:CompareValidator>

hope this will help you!
Reena Jain replied to mani on 12-May-11 03:32 AM
hi,

try this

foreach ( li in ddlmothertongue.Items)
{
  if (li.Value.ToString() == textbox.Text)
  {
    
  }
}

hope this will help you
TSN ... replied to mani on 12-May-11 03:56 AM
hi,...

string txtboxvalue=txtValue.Text;
if (ddlCustomerNumber.Items.FindByText(txtboxvalue) != null)
{
// show your specified message
}
else
{
 //save it here...
}


hope this helps you...
mani replied to TSN ... on 12-May-11 04:26 AM
is there any java script for this same condition...to perform at browser side..

 string txtboxvalue = txtmothertongue.Text;

      if (ddlmothertongue.Items.FindByText(txtboxvalue) != null)
      {
        messagebox("Already Available in Mothertoung list!!");
      }
TSN ... replied to mani on 12-May-11 04:38 AM
You can iterate through the list like this i have given it in jquery..

var s="False";

$('#ListName option').each(function(){

//here this can be refered as an option.. like

if(this.val() == anyvalue)

{

s="True"

}

});

IF(s=False)
 {
// try to save the data
|}
else
{
 //alert your message...
}

check for  the syntaxes i have written orally.......