检查TextBox是否为空并返回MessageBox?

我做了这个语句来检查TextBox是否为空,但MessageBox总是显示TextBox是否为空。

private void NextButton_Click(object sender, EventArgs e) { decimal MarkPoints, x, y; x = HoursNumericUpDown.Value; y = MarkNumericUpDown.Value; MarkPoints = x * y; //decimal MarkPoints = (decimal)HoursNumericUpDown.Value * (decimal)HoursNumericUpDown.Value; DataGridViewRow dgvRow = new DataGridViewRow(); DataGridViewTextBoxCell dgvCell = new DataGridViewTextBoxCell(); dgvCell = new DataGridViewTextBoxCell(); dgvCell.Value = MaterialTextBox.Text; dgvRow.Cells.Add(dgvCell); dgvCell = new DataGridViewTextBoxCell(); dgvCell.Value = HoursNumericUpDown.Value; dgvRow.Cells.Add(dgvCell); dgvCell = new DataGridViewTextBoxCell(); dgvCell.Value = MarkNumericUpDown.Value; dgvRow.Cells.Add(dgvCell); dgvCell = new DataGridViewTextBoxCell(); dgvCell.Value = MarkPoints; dgvRow.Cells.Add(dgvCell); dataGridView1.Rows.Add(dgvRow); MaterialTextBox.Clear(); HoursNumericUpDown.Value = HoursNumericUpDown.Minimum; MarkNumericUpDown.Value = MarkNumericUpDown.Minimum; if (String.IsNullOrEmpty(MaterialTextBox.Text)) { MessageBox.Show("Enter Material Name Please.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); //dataGridView1.Rows.Clear(); } else { /*if (MarkNumericUpDown.Value  50 && MarkNumericUpDown.Value <= 64) { dataGridView1.Rows[index].Cells[4].Value = "F"; }*/ 

请尝试这种情况:

 if (string.IsNullOrWhiteSpace(MaterialTextBox.Text)) { // Message box } 

这将处理一些只包含空白字符的字符串,你不必处理字符串相等,这有时会很棘手

好吧,在检查文本框是否为空之前,您正在清除文本框

 /* !! This clears the textbox BEFORE you check if it's empty */ MaterialTextBox.Clear(); HoursNumericUpDown.Value = HoursNumericUpDown.Minimum; MarkNumericUpDown.Value = MarkNumericUpDown.Minimum; if (String.IsNullOrEmpty(MaterialTextBox.Text)) { MessageBox.Show("Enter Material Name Please.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); //dataGridView1.Rows.Clear(); } 

使用如下内容:

 if (String.IsNullOrEmpty(MaterialTextBox.Text)) 

尝试执行以下操作

 if (String.IsNullOrEmpty(MaterialTextBox.Text) || String.IsNullOrWhiteSpace(MaterialTextBox.Text)) { //do job } else { MessageBox.Show("Please enter correct path"); } 

希望能帮助到你

加上@ tjg184所说的,你可以做点什么……

 if (String.IsNullOrEmpty(MaterialTextBox.Text.Trim())) 

 if (MaterialTextBox.Text.length==0) { message }