reading of the first two characters

0

I am taking the reading of a scaner in a textbox but I need to make a function that only allows the scans that start with "3S", otherwise it tells me error. I use this method which I only declare within the event TextChanged of textbox1 in this case. string a and string b are this case " 3S " and " 3s ", with which I determine that with they should start the text. Take the reading but I'm removing the " 3S ", I need all the reading.

private void opcion1(TextBox txt)
{   
   string s = txt.Text;
   string a = Properties.Settings.Default.op11;
   string b = Properties.Settings.Default.op12;

   if(s != "")
   {     
      if(s.Length >= 2)
      {
         if (s.startswith(a) || s.startswith(b))  
         {

            if (s.Length > 2)             
            {         
            }
            else
            {
                 s = "";
            }
            txt.Text = s;
       }
   }
}
    
asked by Ronald López 24.05.2018 в 15:46
source

3 answers

2

I would modify your method to return a bool if the business rule you indicate occurs. It would also avoid passing a TextBox as a parameter since that causes you to modify the value of its Text property as it is an object that is passed as a reference to your method.

private bool opcion1(string txt)
{
    bool resultado = false;
    string a = Properties.Settings.Default.op11;
    string b = Properties.Settings.Default.op12;

    if (!string.IsNullOrWhiteSpace(txt))
    {
        if (txt.Length >= 2)
        {
            if (txt.StartsWith(a) || txt.StartsWith(b))
            {
                resultado = true; // dejaremos pasar
            }
        }
    }

    return resultado;
}
    
answered by 24.05.2018 / 16:19
source
0

This is how I have the code and it works well for me because I extract "3S" when it has this one, the detail is that it reads other values that do not have "3S", I must apply a condition that if different from "3S" clean the field.

Private void opcion1(string txt) 

string s = txt.Text;
        string a = "3S";
        string b = "3s";

        if (s != "")
        {
            if (s.Length >= 2)
            {
                if (s.StartsWith(a) || s.StartsWith(b))
                {
                    if (s.Length > 2)
                    {
                        //MessageBox.Show(s.Length.ToString());
                        s = s.Substring(2);
                    }
                    else
                        s = "";
                }

                txt.Text = s;
            }
        }
    
answered by 24.05.2018 в 20:07
-1

Ronald, I would swear that you have the problem by assigning s= "" and then leaving it again in txt.Texto . When s starts with a or b its length is 2 and therefore empty the string and return it to txt .

    
answered by 24.05.2018 в 16:08