Okezie Victor Ответов: 2

Пожалуйста, мне нужна помощь в том, как я могу заставить эту часть моего кода работать, так как я постоянно получаю предупреждающее сообщение "обнаружен недостижимый код"


private bool ValidData()
        {
                 
            // Initialize function return value
            return false;
            
            // Test CustomerID is complete
            if (((service_NoTextBox.Text == String.Empty) 
                    ||(Information.IsNumeric(service_NoTextBox.Text) == false)))
            {
                // Required employee ID is not complete
                MessageBox.Show("Service Number is not complete", "Promotion List Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                service_NoTextBox.Focus();
                service_NoTextBox.SelectAll();
            }
            else if (((file_NoTextBox.Text == String.Empty)
                        || (Information.IsNumeric(file_NoTextBox.Text) == false)))
            {
                // Validate File Number
                MessageString = "File Number is required and must be in five digit format.";
                MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                file_NoTextBox.Focus();
                file_NoTextBox.SelectAll();
            }
            else if (((nameTextBox.Text == String.Empty)
                        || (Information.IsNumeric(nameTextBox.Text) == true)))
            {
                // Validate  Name
                MessageString = "Name is required in alphabet format.";
                MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                nameTextBox.Focus();
                nameTextBox.SelectAll();
            }
            else if (((new_RankTextBox.Text == String.Empty)
                        || (Information.IsNumeric(new_RankTextBox.Text) == true)))
            {
                // Validate New Rank
                MessageString = "New Rank is required in alphabet format.";
                MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                new_RankTextBox.Focus();
                new_RankTextBox.SelectAll();
            }
            else if (((old_RankTextBox.Text == String.Empty)
                        || (Information.IsNumeric(old_RankTextBox.Text) == true)))
            {
                // Validate Previous Rank
                MessageString = "Old Rank is required in alphabetic form.";
                MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                old_RankTextBox.Focus();
                old_RankTextBox.SelectAll();
            }
            else if (((stationTextBox.Text == String.Empty)
                        || (Information.IsNumeric(stationTextBox.Text) == true)))
            {
                // Validate State
                MessageString = "State is required in letter form.";
                MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                stationTextBox.Focus();
                stationTextBox.SelectAll();
            }
            else if (((comboBox1.Text == String.Empty)
                        || (Information.IsNumeric(comboBox1.Text) == true)))
            {
                // Command Is required
                MessageString = "Please Enter Command.";
                MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                comboBox1.Focus();
                comboBox1.SelectAll();
            }
            else if (((comboBox2.Text == String.Empty)
                        || (Information.IsNumeric(comboBox2.Text) == true)))
            {
                // Validate 
                MessageString = "State of Origin must be in Alphabet form.";
                MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                comboBox2.Focus();
                comboBox2.SelectAll();
            }
                
            else
            {
                // All of the data is valid
                return true;
            }
                
        }


Что я уже пробовал:

Я попытался установить ValidData = false и true, но я также не могу назначить тип метода

2 Ответов

Рейтинг:
5

Karthik_Mahalingam

обновленное решение в соответствии с комментариями Дэйва Кресковяка удалило return ключевое слово из каждого блока условий.
замените его возвращаемой переменной и используйте ее в блоке требуемых условий и верните переменную.

private bool ValidData()
       {

           // Initialize function return value
           bool returnValue = false;

           // Test CustomerID is complete
           if (((service_NoTextBox.Text == String.Empty)
           || (Information.IsNumeric(service_NoTextBox.Text) == false)))
           {
               // Required employee ID is not complete
               MessageBox.Show("Service Number is not complete", "Promotion List Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
               service_NoTextBox.Focus();
               service_NoTextBox.SelectAll();
           }
           else if (((file_NoTextBox.Text == String.Empty)
           || (Information.IsNumeric(file_NoTextBox.Text) == false)))
           {
               // Validate File Number
               MessageString = "File Number is required and must be in five digit format.";
               MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
               file_NoTextBox.Focus();
               file_NoTextBox.SelectAll();
           }
               .
               .
               .
               .

           else
           {

               returnValue = true;
           }
           return returnValue;

       }
   }


Dave Kreskowiak

Это плохая практика-иметь в методе более одного оператора return. Это ужасная практика-иметь их так чертовски много.

Karthik_Mahalingam

Да, Дэйв, ты прав, я просто сосредоточился на устранении ошибки.
обновили решение.

Richard Deeming

Это еще один аргумент "табуляции против пробелов". Я за то, чтобы иметь несколько операторов return, если это делает код чище. :)

Karthik_Mahalingam

:) это зависит от сценария

Okezie Victor

Спасибо @Dave, Karthik и Richard.

Karthik_Mahalingam

добро пожаловать Оквзи

Рейтинг:
19

Thomas Daniels

Первая строка вашего метода return false;, так что ваш метод немедленно вернется false вызывающему абоненту, и все, что после этой строки будет проигнорировано ("недоступно").

Только вернуться false когда вы замечаете, что "данные" на самом деле недействительны.

Комментарий над вашим "return false" говорит: "Initialize function return value", так что если это то, что вы хотите сделать, то вы можете сделать что-то вроде bool returnValue = false; в верхней части и в конце функции, return returnValue; (и перемены returnValue в вашем методе, когда это необходимо).