如何在保存之前验证文本框

时间:2014-03-19 23:55:51

标签: c# textbox

我得到了这段代码,我要找的是在保存之前验证文本框。现在,如果我填写文本框,那么我清除其中任何一个它仍然保存。我怎么可能在保存之前检查是否全部填满了?我试图为textchanged事件添加处理程序,但我没有工作。任何建议都将受到赞赏,欢呼。


    public partial class frmTrainer : Form
    {
        public frmTrainer()
        {
            InitializeComponent();

            // We initialize new event handlers for the subjects textboxes
            this.englishTextBox.KeyPress += new KeyPressEventHandler(englishTextBox_KeyPress);
            this.mathsTextBox.KeyPress += new KeyPressEventHandler(mathsTextBox_KeyPress);
            this.physicsTextBox.KeyPress += new KeyPressEventHandler(physicsTextBox_KeyPress);
        }

        // We create a public list for all the textbox controls in the form 
        public List textBoxes = new List();

        private void frmTrainer_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'rCMDataSet.Students_Credentials' table. You can move, or remove it, as needed.
            this.students_CredentialsTableAdapter.Fill(this.rCMDataSet.Students_Credentials);

            // We initialize the List of textboxes
            textBoxAdd();
        }

        // We create method stubs for the KeyPress event on the subjects textboxes
        // to allow them receive only numeric inputs
        private void englishTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
                MessageBox.Show("Numeric input accepted only");
            }
        }

        private void mathsTextBox_KeyPress(object sender, KeyPressEventArgs e) 
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
                MessageBox.Show("Numeric input accepted only");
            }            
        }

        private void physicsTextBox_KeyPress(object sendet, KeyPressEventArgs e) 
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
                MessageBox.Show("Numeric input accepted only");
            }            
        }

        // We create a method to add each textbox to the List
        private void textBoxAdd()
        {
            textBoxes.Add(studentIDTextBox);
            textBoxes.Add(first_NameTextBox);
            textBoxes.Add(last_NameTextBox);
            textBoxes.Add(usernameTextBox);
            textBoxes.Add(passwordTextBox);
            textBoxes.Add(englishTextBox);
            textBoxes.Add(mathsTextBox);
            textBoxes.Add(physicsTextBox);
            textBoxes.Add(trainerIDTextBox);
        }

        // We create a private method to validate the textboxes
        private void CheckTextBox()
        {
            foreach(TextBox txt in textBoxes)
            {
                if (string.IsNullOrWhiteSpace(txt.Text))
                {
                    MessageBox.Show("Please insert data correctly");
                }
            }
        }

        private void students_CredentialsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.CheckTextBox();

            try
            { 
                //this.Validate();
                this.students_CredentialsBindingSource.EndEdit();
                this.tableAdapterManager.UpdateAll(this.rCMDataSet);
                MessageBox.Show("Data saved successfully");
            }
            catch(System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void toolStripExit_Click(object sender, EventArgs e)
        {
            // We disable the automatic validation when clicking Exit button
            this.AutoValidate = AutoValidate.Disable;

            // We call the method to close the application
            Application.Exit();
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            // We disable the navigation buttons to prevent any skipping errors
            this.bindingNavigatorMoveFirstItem.Enabled = false;
            this.bindingNavigatorMoveLastItem.Enabled = false;
            this.bindingNavigatorMoveNextItem.Enabled = false;
            this.bindingNavigatorMovePreviousItem.Enabled = false;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您是否尝试在文本框文本中使用String.Trim方法,如:

foreach(TextBox txt in textBoxes)
        {
            //trim whitespaces from text at both ends and might be better to operate on a string

            String text = txt.ToString();
            text.Trim();
            if (string.IsNullOrWhiteSpace(text))
            {
                MessageBox.Show("Please insert data correctly");
            }
        }

答案 1 :(得分:0)

students_CredentialsBindingNavigatorSaveItem_Click事件中,当您将CheckTextBox方法调用为"验证"除了显示MessageBox之外,您基本上没有对空控件做任何事情。你应该做的是每当找到空输入时在验证方法上返回一个布尔值:

    private bool CheckTextBox()
    {
        bool isValid = true;
        foreach(TextBox txt in textBoxes)
        {
            if (string.IsNullOrWhiteSpace(txt.Text))
            {
                isValid = false;
                MessageBox.Show("Please insert data correctly");
                break; //You only need one invalid input to prevent saving
            }
        }
        return isValid;
    }

在Click事件中,检查方法的返回值,如果检测到无效输入则退出事件:

    private void students_CredentialsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        if(!this.CheckTextBox()) return; //Stop executing code if there's invalid input

        try
        { 
            //this.Validate();
            this.students_CredentialsBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.rCMDataSet);
            MessageBox.Show("Data saved successfully");
        }
        catch(System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }