C# 如何在保存前验证文本框

C# 如何在保存前验证文本框,c#,textbox,C#,Textbox,我得到了这段代码,我要找的是在保存之前验证文本框。现在,如果我填充文本框,那么我会清除它们中的任何一个,不管怎样,它都会保存下来。我怎么可能在保存前检查这些文件是否都已填写?我试图为textchanged事件添加处理程序,但没有成功。欢迎提出任何建议,干杯 public partial class frmTrainer : Form { public frmTrainer() { InitializeComponent()

我得到了这段代码,我要找的是在保存之前验证文本框。现在,如果我填充文本框,那么我会清除它们中的任何一个,不管怎样,它都会保存下来。我怎么可能在保存前检查这些文件是否都已填写?我试图为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;
        }
    }
}

是否尝试对文本框文本使用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");
            }
        }

students\u CredentialsBindingNavigatorSaveItem\u单击
事件中,当您调用
复选框
方法来“验证”控件时,除了显示
消息框
外,您基本上没有对空控件做任何操作。当发现空输入时,应在验证方法上返回布尔值:

    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);
        }
    }

嗨,约翰,你说的“填充”或“填充”是什么意思?很抱歉,在您的问题中,我没有得到您想要的内容。在不太更改现有代码的情况下,您可以在
复选框中返回一个布尔值,表示成功或失败。如果在复选框中检测到任何无效数据,请不要将任何内容保存在
学生\u凭证绑定导航器SaveItem\u Click()
中。还是我遗漏了什么?费尔南德斯我怎么能做到?谢谢