Validating every textbox for every single textbox to be INT in c#

Viewed 72

Hi i searched online for this code

        con.Open();
        int parsedValue;
        if (!int.TryParse(txtCCL.Text, out parsedValue))// if not an integer return message below
        {
            MessageBox.Show("This is a number only field");
            return;
        }
        else
        {
        }

like in the txtCCL.Text how do i call check multiple textboxes like

        con.Open();
        int parsedValue;
        if (!int.TryParse(txtCCL.Text||txtA.text||txtB.text, out parsedValue))
        {
            MessageBox.Show("This is a number only field");
            return;
        }
        else
        {
        }

Thanks in advance

2 Answers

You have to iterate all the text boxes.

TryParse can not take multiple text boxes as input.

    //LOOP ALL CONTROLS AND FIND TEXT BOXES
    foreach (TextBox txtBox in this.Controls.OfType<TextBox>())
    {
       int number;

       bool result = Int32.TryParse(txtBox.Text, out number);

       if (result)
       {
           //PRINT TEXT BOX NAME WHICH CAN BE CONVERTIBLE
           MessageBox.Show(txtBox.Name + " is a number only field");
       }
    }

You can use TryParse method with if condition with multiple check

int v1;
    if (int.TryParse(txtCCL.Text, out v1) && int.TryParse(txt2.Text,out v1) && int.TryParse(txt3.Text,out v1))
    {
            //is integer
    }
Related