简体   繁体   中英

How to compare and check text box value with label value in event of text changed?

I have a text box and label sitting next to each others. Label's text value comes from a drop down list. I have to turn the focus of text box to itself if, label's value is smaller than text box value and it goes on until, right value is entered in textbox. Can You help me?

This is my code:- .aspx file:-

<div class="row mb10">
   <asp:Label runat="server" ID="lbl_Adults" CssClass="col-lg-2 control-label" Text="Adults : " AssociatedControlID="txt_Adults"></asp:Label>
      <div class="col-lg-6">
          <div class="col-lg-4" style="margin-left:-15px;">
              <asp:TextBox runat="server" ID="txt_Adults" CssClass="form-control" OnTextChanged="txt_Adults_TextChanged" AutoPostBack="true"></asp:TextBox>
              <asp:RequiredFieldValidator Font-Bold="true" ForeColor="Red" runat="server" ID="req_Adults" ControlToValidate="txt_Adults" ErrorMessage="Enter No. of Adults"></asp:RequiredFieldValidator>
          </div>
          <div class="col-lg-8" style="font-family:'Copperplate Gothic'">
                Only <asp:Label runat="server" ID="lbl_No_Of_Adults"></asp:Label> Adult(s) allowed.
          </div>
    </div>
</div>

Here's .cs file code:-

protected void txt_Adults_TextChanged(object sender, EventArgs e)
  {

     while (true)
     {
         if (txt_Adults==null)
         {
             txt_Adults.Text = Convert.ToString("0");
             txt_Adults.Focus();
             //txt_Adults_TextChanged(sender, e);
         }
         else if (Convert.ToInt32(txt_Adults.Text) > Max_NoAdults)
         {
             txt_Adults.Text = Convert.ToString("0");
             txt_Adults.Focus();
             //txt_Adults_TextChanged(sender, e);

         }
         else
         {
             NoAdults = Convert.ToInt32(txt_Adults.Text);
             //NoAdults is a static variable that collects final(right) value of txt_Adults.text;
             break;
         }

     }

 }

Simply do this

protected void txt_Adults_TextChanged(object sender, EventArgs e)
{
   //this condition will always be true unless and until both the `Text`
   //string are same
   if (lbl_No_Of_Adults.Text.Trim() != txt_Adults.Text.Trim())
   {
      txt_Adults.Focus(); 
   }
}

Else if you want to match the condition ONLY if Label value is lesser than TextBox do this.

protected void txt_Adults_TextChanged(object sender, EventArgs e)
{
   int a = 0 , b =0;
   int.TryParse(lbl_No_Of_Adults.Text.Trim(), out  a);
   int.TryParse(txt_Adults.Text.Trim(), out  b);

   if (a < b)
   {
      txt_Adults.Focus(); 
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM