I made this statement to check if TextBox is empty, but the MessageBox always shows up
wether the TextBox is empty or not.
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)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[1].Cells[4].Value = "F";
}
else if (MarkNumericUpDown.Value > 50 && MarkNumericUpDown.Value <= 64)
{
dataGridView1.Rows[index].Cells[4].Value = "F";
}*/
![]()
informatik01
15.8k10 gold badges74 silver badges103 bronze badges
asked May 27, 2011 at 18:45
2
Try this condition instead:
if (string.IsNullOrWhiteSpace(MaterialTextBox.Text)) {
// Message box
}
This will take care of some strings that only contain whitespace characters and you won’t have to deal with string equality which can sometimes be tricky
answered May 27, 2011 at 18:49
DypplDyppl
12k9 gold badges46 silver badges68 bronze badges
7
Well, you are clearing the textbox right before you check if it’s empty
/* !! 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();
}
answered May 27, 2011 at 19:12
DypplDyppl
12k9 gold badges46 silver badges68 bronze badges
1
Use something such as the following:
if (String.IsNullOrEmpty(MaterialTextBox.Text))
answered May 27, 2011 at 18:47
tjg184tjg184
4,4381 gold badge26 silver badges54 bronze badges
1
Try doing the following
if (String.IsNullOrEmpty(MaterialTextBox.Text) || String.IsNullOrWhiteSpace(MaterialTextBox.Text))
{
//do job
}
else
{
MessageBox.Show("Please enter correct path");
}
Hope it helps
answered Nov 28, 2016 at 5:44
![]()
cell-incell-in
6892 gold badges10 silver badges25 bronze badges
Adding on to what @tjg184 said, you could do something like…
if (String.IsNullOrEmpty(MaterialTextBox.Text.Trim()))
…
answered May 27, 2011 at 18:59
contactmattcontactmatt
17.9k40 gold badges125 silver badges185 bronze badges
0
if (MaterialTextBox.Text.length==0)
{
message
}
answered Jul 30, 2013 at 9:44
For multiple text boxes — add them into a list and show all errors into 1 messagebox.
// Append errors into 1 Message Box
List<string> errors = new List<string>();
if (string.IsNullOrEmpty(textBox1.Text))
{
errors.Add("User");
}
if (string.IsNullOrEmpty(textBox2.Text))
{
errors.Add("Document Ref Code");
}
if (errors.Count > 0)
{
errors.Insert(0, "The following fields are empty:");
string message = string.Join(Environment.NewLine, errors);
MessageBox.Show(message, "errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
answered May 15, 2020 at 12:27
![]()
EduardsEduards
1,63011 silver badges31 bronze badges
Becasue is a TextBox already initialized would be better to control if there is something in there outside the empty string (which is no null or empty string I am afraid). What I did is just check is there is something different than «», if so do the thing:
if (TextBox.Text != "") //Something different than ""?
{
//Do your stuff
}
else
{
//Do NOT do your stuff
}
answered Jul 22, 2020 at 12:58
![]()
JuanoJuano
631 silver badge10 bronze badges
I’m trying to validate a text box in a form to not having empty string if the user didn’t entered anything in the text box, so if the text box was empty, the user has to enter a value ,and my code was like this, but it is not working
public int TextBox_Validation(string sender)
{
try
{
if (string.IsNullOrEmpty(sender))
{
MessageBox.Show("Please enter a value");
}
}
catch
{
int num = int.Parse(sender);
return 0;
}
return 0;
}
Bala R
106k23 gold badges195 silver badges209 bronze badges
asked Jun 9, 2011 at 18:32
6
Sender generally refers to just the sending object, so check that you are sending the text of the textbox and not a reference to the textbox.
Also, you are always returning zero. Change your code to the following. You will return a 1 if the validation passes and 0 if it fails. Incidentally, you should be using a boolean instead of an int. I commented out a line below because it isn’t doing anything constructive in this situation:
try
{
if (string.IsNullOrEmpty(sender))
{
MessageBox.Show("Please enter a value");
return 0;
}
}
catch
{
//int num = int.Parse(sender);
return 0;
}
return 1;
I recommend your change your method to the below. You don’t need your try {} catch {} because isNullOrEmpty covers the lone potential null issue:
bool ValidateText(string Text)
{
if (string.IsNullOrEmpty(Text))
{
MessageBox.Show("Please enter a value");
return false;
}
return true;
}
answered Jun 9, 2011 at 18:35
Devin BurkeDevin Burke
13.5k11 gold badges54 silver badges81 bronze badges
2
public bool TextBox_Validation(string sender) {
return !string.IsNullOrEmpty(sender);
}
if(TextBox_Validation(textbox1.Value)) {
//OK
} else {
MessageBox.Show("Please enter a value");
//ETC
}
answered Jun 9, 2011 at 18:42
The MaskThe Mask
16.8k36 gold badges110 silver badges182 bronze badges
You aren’t throwing an exception so you won’t make it into the catch block.
public int TextBox_Validation(string value)
{
int integer = 0;
if( string.IsNullOrEmpty( value ) )
{
MessageBox.Show( "Please enter a value" );
}
else
{
int.TryParse( value, out integer );
}
return integer;
}
answered Jun 9, 2011 at 18:42
You’re algorithm is incorrect. The catch block is used to catch errors that occur within the preceeding try block. In this case, I don’t see a runtime error occurring so there probably is no need to a try/catch block, but I’ll leave in for example sake. Also, your function doesn’t provide a way for the program to know if it was empty or not. You could return 0 if it is empty or 1 if not. or return boolean true or false. Maybe a function like this would be better:
public bool TextBox_Validation(string sender)
{
try
{
if (string.IsNullOrEmpty(sender))
{
MessageBox.Show("Please enter a value");
return false;
}
else
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
answered Jun 9, 2011 at 18:43
Nick RolandoNick Rolando
25.7k13 gold badges78 silver badges117 bronze badges
You can try something like this instead
if (String.IsNullOrEmpty(txtTextBox.Text))
{
MessageBox.Show("Enter Value Please.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
//whatever u need to do
}
answered Jun 9, 2011 at 18:43
knurdyknurdy
4966 silver badges18 bronze badges
try-catch blocks are useless, method should return bool and should not show any messages. It is a bad practice to do not related things in a single method (show messages, return some meaningless numbers, etc). If it is validating method, it should tell you only one thing — whether passed string is valid or not (just a single bool in your case), that’s all. You should consider showing messages to user in another method. And one more thing — depending on technology you are using, it may have better validation support (validation in WF, validation rules in WPF, etc), use them, instead of handling some input events
answered Jun 9, 2011 at 18:43
I’m trying to validate a text box in a form to not having empty string if the user didn’t entered anything in the text box, so if the text box was empty, the user has to enter a value ,and my code was like this, but it is not working
public int TextBox_Validation(string sender)
{
try
{
if (string.IsNullOrEmpty(sender))
{
MessageBox.Show("Please enter a value");
}
}
catch
{
int num = int.Parse(sender);
return 0;
}
return 0;
}
Bala R
106k23 gold badges195 silver badges209 bronze badges
asked Jun 9, 2011 at 18:32
6
Sender generally refers to just the sending object, so check that you are sending the text of the textbox and not a reference to the textbox.
Also, you are always returning zero. Change your code to the following. You will return a 1 if the validation passes and 0 if it fails. Incidentally, you should be using a boolean instead of an int. I commented out a line below because it isn’t doing anything constructive in this situation:
try
{
if (string.IsNullOrEmpty(sender))
{
MessageBox.Show("Please enter a value");
return 0;
}
}
catch
{
//int num = int.Parse(sender);
return 0;
}
return 1;
I recommend your change your method to the below. You don’t need your try {} catch {} because isNullOrEmpty covers the lone potential null issue:
bool ValidateText(string Text)
{
if (string.IsNullOrEmpty(Text))
{
MessageBox.Show("Please enter a value");
return false;
}
return true;
}
answered Jun 9, 2011 at 18:35
Devin BurkeDevin Burke
13.5k11 gold badges54 silver badges81 bronze badges
2
public bool TextBox_Validation(string sender) {
return !string.IsNullOrEmpty(sender);
}
if(TextBox_Validation(textbox1.Value)) {
//OK
} else {
MessageBox.Show("Please enter a value");
//ETC
}
answered Jun 9, 2011 at 18:42
The MaskThe Mask
16.8k36 gold badges110 silver badges182 bronze badges
You aren’t throwing an exception so you won’t make it into the catch block.
public int TextBox_Validation(string value)
{
int integer = 0;
if( string.IsNullOrEmpty( value ) )
{
MessageBox.Show( "Please enter a value" );
}
else
{
int.TryParse( value, out integer );
}
return integer;
}
answered Jun 9, 2011 at 18:42
You’re algorithm is incorrect. The catch block is used to catch errors that occur within the preceeding try block. In this case, I don’t see a runtime error occurring so there probably is no need to a try/catch block, but I’ll leave in for example sake. Also, your function doesn’t provide a way for the program to know if it was empty or not. You could return 0 if it is empty or 1 if not. or return boolean true or false. Maybe a function like this would be better:
public bool TextBox_Validation(string sender)
{
try
{
if (string.IsNullOrEmpty(sender))
{
MessageBox.Show("Please enter a value");
return false;
}
else
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
answered Jun 9, 2011 at 18:43
Nick RolandoNick Rolando
25.7k13 gold badges78 silver badges117 bronze badges
You can try something like this instead
if (String.IsNullOrEmpty(txtTextBox.Text))
{
MessageBox.Show("Enter Value Please.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
//whatever u need to do
}
answered Jun 9, 2011 at 18:43
knurdyknurdy
4966 silver badges18 bronze badges
try-catch blocks are useless, method should return bool and should not show any messages. It is a bad practice to do not related things in a single method (show messages, return some meaningless numbers, etc). If it is validating method, it should tell you only one thing — whether passed string is valid or not (just a single bool in your case), that’s all. You should consider showing messages to user in another method. And one more thing — depending on technology you are using, it may have better validation support (validation in WF, validation rules in WPF, etc), use them, instead of handling some input events
answered Jun 9, 2011 at 18:43
|
Заблокирован |
|
|
1 |
|
|
24.05.2012, 20:05. Показов 89825. Ответов 31
Добрый всем день! Как можно делать, чтобы в таблицу не добавлялись значения если в textbox не введено значение?
__________________
0 |
|
Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
|
|
24.05.2012, 20:12 |
2 |
|
Как вариант делать кнопку неактивной в событии text_changed, если textbox равен null. Или же при нажатии проверять, введено ли что-либо в textbox.
0 |
|
Заблокирован |
|
|
24.05.2012, 20:23 [ТС] |
3 |
|
все равно добавляются значения в таблицу(( Мне нужно, если хоть в одном textbox пусто, в таблицу данные не заносились! Как это можно прописать?
0 |
|
WorldException Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
||||
|
24.05.2012, 20:29 |
4 |
|||
|
Например:
Добавлено через 31 секунду
2 |
|
Заблокирован |
||||
|
24.05.2012, 20:31 [ТС] |
5 |
|||
|
А код «ничего не делаем» какой?) не проходит ничего на ум(( Добавлено через 1 минуту
А в if не знаю что прописать(
1 |
|
WorldException Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
||||
|
24.05.2012, 20:34 |
6 |
|||
|
Мне нужно, если хоть в одном textbox пусто, в таблицу данные не заносились!
А код «ничего не делаем» какой?) Намёк ясен? Добавлено через 59 секунд
Добавлено через 1 минуту Добавлено через 27 секунд
0 |
|
Заблокирован |
|
|
24.05.2012, 20:36 [ТС] |
7 |
|
К сожалению эффекта никакого(((
0 |
|
Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
|
|
24.05.2012, 20:37 |
8 |
|
Полностью код можно глянуть?
0 |
|
Заблокирован |
|
|
24.05.2012, 20:40 [ТС] |
9 |
|
В этом textbox ничего не прописано!!! А если весь код посылать, то он большой слишком.. Просто есть 3 textbox и кнопочка «Добавить» в таблицу DatagridView ! А мне нужно сделать так, чтобы если хоть в один textbox не занесли значение, то добавление в таблицу не происходит!!!!
0 |
|
WorldException Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
||||
|
24.05.2012, 20:44 |
10 |
|||
|
Ну вот сразу бы так..
0 |
|
Заблокирован |
|
|
24.05.2012, 20:48 [ТС] |
11 |
|
А можете подсказать код «Ничего не добавляем» пожалуйста?)
0 |
|
Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
|
|
24.05.2012, 20:57 |
12 |
|
Ну, оповестите пользователя о том, что нужно заполнить все поля для того, чтобы добавить данные в таблицу. С помощью MessageBox, например.
0 |
|
Заблокирован |
|
|
24.05.2012, 21:01 [ТС] |
13 |
|
Это все понятно… но в таблицу данные заносятся!!!! А нужно, чтобы когда нажималась кнопка «Добавить» выскакивала окошка что поле ввода пусто и В ТАБЛИЦУ ДАННЫЕ НЕ ЗАНОСИЛИСЬ!!! т.е. чтобы кроме появления окошка ничего не появлялось!!
0 |
|
Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
|
|
24.05.2012, 21:02 |
14 |
|
Покажите код на кнопке «Добавить»
0 |
|
Заблокирован |
||||
|
24.05.2012, 21:04 [ТС] |
15 |
|||
Вот весь код на кнопки ДОБАВИТЬ)
0 |
|
WorldException Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
||||
|
24.05.2012, 21:07 |
16 |
|||
|
Вы вот так попробуйте…
1 |
|
Заблокирован |
|
|
24.05.2012, 21:11 [ТС] |
17 |
|
Все гениально просто… Спасибо все заработало Добавлено через 1 минуту
0 |
|
Банальное исключение 127 / 95 / 12 Регистрация: 31.03.2010 Сообщений: 314 Записей в блоге: 1 |
|
|
24.05.2012, 21:11 |
18 |
|
Всегда пожалуйста.
2 |
|
Заблокирован |
|
|
24.05.2012, 21:15 [ТС] |
19 |
|
А вы случайно не знаете, как можно сделать, чтобы в TextBoxe слово начиналось с большой буквы, т.е. заглавной??
0 |
|
Pooh 407 / 359 / 82 Регистрация: 07.10.2009 Сообщений: 558 |
||||
|
25.05.2012, 13:36 |
20 |
|||
|
как можно сделать, чтобы в TextBoxe слово начиналось с большой буквы
По-моему, так!
4 |
- HowTo
- C# Howtos
- Check if TextBox Is Empty in C#
- Check if a TextBox Is Empty With the
String.IsNullOrEmpty()Function inC# - Check if a TextBox Is Empty With the
TextBox.Text.LengthProperty inC#

This tutorial will discuss how to check if a text box is empty or not in C#.
Check if a TextBox Is Empty With the String.IsNullOrEmpty() Function in C#
The String.IsNullOrEmpty() function checks whether a string is null or empty or not in C#. The String.IsNullOrEmpty() function has a boolean return type and returns true if the string is either null or empty and otherwise returns false. We can use the String.IsNullOrEmpty() function on the string inside the TextBox.Text property to check whether the text inside the text box is empty or not. See the following code example.
using System;
using System.Windows.Forms;
namespace check_if_textbox_is_empty
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox1.Text))
{
label1.Text = "TEXT BOX IS EMPTY";
}
}
}
}
Output:

In the above code, we checked whether the text box is empty or not with the String.IsEmptyOrNot() function in C#. We can also use the String.IsNullOrWhitespace() function to check whether there are whitespaces inside the text box or not, as shown below.
using System;
using System.Windows.Forms;
namespace check_if_textbox_is_empty
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhitespace(textBox1.Text))
{
label1.Text = "TEXT BOX IS EMPTY";
}
}
}
}
This approach also takes the whitespaces into consideration and displays the error message TEXT BOX IS EMPTY if there are only whitespaces inside the text box.
Check if a TextBox Is Empty With the TextBox.Text.Length Property in C#
The TextBox.Text.Length property gets the length of the text inside the text box in C#. We can use the TextBox.Text.Length == 0 condition inside the if statement to check if the text box is empty or not. See the following code example.
using System;
using System.Windows.Forms;
namespace check_if_textbox_is_empty
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length == 0)
{
label1.Text = "TEXT BOX IS EMPTY";
}
}
}
}
Output:

In the above code, we checked whether the text box is empty or not with the TextBox.Text.Length property in C#. This method is not recommended because it does not take whitespaces into consideration.


Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
Related Article — Csharp GUI

- Remove From My Forums
-
Вопрос
-
Всем доброго времени суток! Подскажите, пожалуйста, как реализовать проверку вводимых значений в textbox? Допустим, есть следующий код:
int tax, minute, rez;
//конвертируем строки в целые числа
tax = Convert.ToInt32(taxbox.Text);
minute = Convert.ToInt32(minutebox.Text);//Считаем по формуле
rez = tax * minute / 60;//Конвертируем из целого числа в строковое представление, а результат вставляем в label(summ)
this.summ.Text = rez.ToString();На данной форме, перед осуществлением рассчетов и после ввода данных, предпологается произвести проверку на (1) пустое поле и (2) только целые числа. Проблема вся в том, что никак не могу организовать цикл так, чтобы рассчеты производились уже после проверки, форма просто зависала при пустых значениях textbox’a, пытаясь выполнить преобразование. Заранее благодарен за помощь!
P.S. Только сейчас увидел раздел learning. Просьба перенести вопрос туда.-
Изменено
10 ноября 2009 г. 8:11
Форматирование кода -
Перемещено
I.Vorontsov
10 ноября 2009 г. 11:36
Более соответствующая тематика (От:Visual C#) -
Перемещено
SachinW
1 октября 2010 г. 22:01
MSDN Forums Consolidation (От:Начинающие разработчики)
-
Изменено
Ответы
-
Можно и таким образом:
if (textBox1.Text == String.Empty)//Проверка на пустоту текстбокса
MessageBox.Show(«Empty»);Добавить в обработчик события ввода(Кроме цифр ввести с клавиатуры ничего не получится):
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
e.Handled = true;
}-
Предложено в качестве ответа
I.Vorontsov
10 ноября 2009 г. 8:08 -
Помечено в качестве ответа
DronOVER
10 ноября 2009 г. 8:11
-
Предложено в качестве ответа
-
private void button1_Click(object sender, EventArgs e) { int result; if (String.IsNullOrEmpty(textBox1.Text) || !Int32.TryParse(textBox1.Text, out result)) { return; } MessageBox.Show(result.ToString()); }-
Помечено в качестве ответа
DronOVER
10 ноября 2009 г. 8:05
-
Помечено в качестве ответа
-
Если попытка преобразования строки в целое удачна, то в нем возвращается число, иначе в нём будет 0. Функция возвращает true или false в зависимости от успеха или неудачи преобразования.
-
Помечено в качестве ответа
DronOVER
10 ноября 2009 г. 8:35
-
Помечено в качестве ответа
On a site I found the TryParse method (how to check if there is a empty textbox in C#) but I don’t know how to use it.
int outputValue=0;
bool isNumber=false;
isNumber=int.TryParse(textBox1.Text, out outputValue);
if(!isNumber)
{
MessageBox.Show("Type numbers in the textboxes");
}
else
{
// some code
}
and how can i solve this for 1+ number of textboxes
![]()
d219
2,6425 gold badges30 silver badges34 bronze badges
asked Jul 3, 2014 at 6:38
4
If you want to check empty for all text box control in your page .Try IsNullOrWhiteSpace
foreach (Control child in this.Controls)
{
TextBox textBox = child as TextBox;
if (textBox != null)
{
if (!string.IsNullOrWhiteSpace(textBox.Text))
{
MessageBox.Show("Text box can't be empty");
}
}
}
answered Jul 3, 2014 at 7:12
![]()
1
You don’t need to use the TryParse function. The TryParse function in your example above will try to convert the text of textBox1 into the value outputValue.
If it succeeds, the boolean isNumber becomes true and the parameter outputValue get’s the value of the Textbox converted to an int.
If it fails, the ‘IsNumber’ property will stay false, and the property outputValue is never changed.
Basiclly, if you need to check if a textbox is empty you can use:
if (string.IsNullOrEmpty(textbox1.Text) || string.IsNullOrEmpty(textbox2.Text) || string.IsNullOrEmpty(textbox3.Text) || string.IsNullOrEmpty(textbox4.Text))
{
// At least 1 textbox is empty.
}
else
{
// All the textboxes are filled in.
}
answered Jul 3, 2014 at 6:41
ComplexityComplexity
5,6266 gold badges38 silver badges83 bronze badges
3
Many ways to complete this task
1. string.IsNullOrEmpty(textbox1.Text)
2. textbox1.Text = string.empty();
3. textbox1.Text = "";
answered Jul 3, 2014 at 6:56
![]()
RahulRahul
5,5456 gold badges33 silver badges57 bronze badges
You can try this:
if(textBox1.Text.length==0) {
//do something
}
answered Apr 20, 2020 at 16:26
you can use the below menioned code
if(!string.IsNullOrEmpty(textbox1.Text))
{
int outputValue=0;
bool isNumber=false;
isNumber=int.TryParse(textBox1.Text, out outputValue);
if(!isNumber)
{
MessageBox.Show("Type numbers in the textboxes");
}
else
{
// some code
}
}
answered Jul 3, 2014 at 6:41
![]()
Dhaval PatelDhaval Patel
7,4216 gold badges36 silver badges70 bronze badges
1
On a site I found the TryParse method (how to check if there is a empty textbox in C#) but I don’t know how to use it.
int outputValue=0;
bool isNumber=false;
isNumber=int.TryParse(textBox1.Text, out outputValue);
if(!isNumber)
{
MessageBox.Show("Type numbers in the textboxes");
}
else
{
// some code
}
and how can i solve this for 1+ number of textboxes
![]()
d219
2,6425 gold badges30 silver badges34 bronze badges
asked Jul 3, 2014 at 6:38
4
If you want to check empty for all text box control in your page .Try IsNullOrWhiteSpace
foreach (Control child in this.Controls)
{
TextBox textBox = child as TextBox;
if (textBox != null)
{
if (!string.IsNullOrWhiteSpace(textBox.Text))
{
MessageBox.Show("Text box can't be empty");
}
}
}
answered Jul 3, 2014 at 7:12
![]()
1
You don’t need to use the TryParse function. The TryParse function in your example above will try to convert the text of textBox1 into the value outputValue.
If it succeeds, the boolean isNumber becomes true and the parameter outputValue get’s the value of the Textbox converted to an int.
If it fails, the ‘IsNumber’ property will stay false, and the property outputValue is never changed.
Basiclly, if you need to check if a textbox is empty you can use:
if (string.IsNullOrEmpty(textbox1.Text) || string.IsNullOrEmpty(textbox2.Text) || string.IsNullOrEmpty(textbox3.Text) || string.IsNullOrEmpty(textbox4.Text))
{
// At least 1 textbox is empty.
}
else
{
// All the textboxes are filled in.
}
answered Jul 3, 2014 at 6:41
ComplexityComplexity
5,6266 gold badges38 silver badges83 bronze badges
3
Many ways to complete this task
1. string.IsNullOrEmpty(textbox1.Text)
2. textbox1.Text = string.empty();
3. textbox1.Text = "";
answered Jul 3, 2014 at 6:56
![]()
RahulRahul
5,5456 gold badges33 silver badges57 bronze badges
You can try this:
if(textBox1.Text.length==0) {
//do something
}
answered Apr 20, 2020 at 16:26
you can use the below menioned code
if(!string.IsNullOrEmpty(textbox1.Text))
{
int outputValue=0;
bool isNumber=false;
isNumber=int.TryParse(textBox1.Text, out outputValue);
if(!isNumber)
{
MessageBox.Show("Type numbers in the textboxes");
}
else
{
// some code
}
}
answered Jul 3, 2014 at 6:41
![]()
Dhaval PatelDhaval Patel
7,4216 gold badges36 silver badges70 bronze badges
1


