Если текстбокс пустой то ошибка

I have a TextBox. And I want to check if it’s empty.

Which way is better

if(TextBox.Text.Length == 0)

or

if(TextBox.Text == '')

?

ΩmegaMan's user avatar

ΩmegaMan

29.2k10 gold badges99 silver badges121 bronze badges

asked Dec 15, 2015 at 20:32

4

You should use String.IsNullOrEmpty() to make sure it is neither empty nor null (somehow):

if (string.IsNullOrEmpty(textBox1.Text))
{
    // Do something...
}

More examples here.

For practical purposes you might also consider using String.IsNullOrWhitespace() since a TextBox expecting whitespace as input probably negates any purpose, except in case of, say, letting the user pick a custom separator for stuff.

AnasSafi's user avatar

AnasSafi

5,0681 gold badge35 silver badges33 bronze badges

answered Dec 15, 2015 at 20:49

Fᴀʀʜᴀɴ Aɴᴀᴍ's user avatar

Fᴀʀʜᴀɴ AɴᴀᴍFᴀʀʜᴀɴ Aɴᴀᴍ

6,0915 gold badges31 silver badges52 bronze badges

I think

string.IsNullOrEmpty(TextBox.Text)

or

string.IsNullOrWhiteSpace(TextBox.Text)

are your best options.

answered Dec 16, 2015 at 2:36

PiotrWolkowski's user avatar

PiotrWolkowskiPiotrWolkowski

8,3386 gold badges47 silver badges67 bronze badges

3

If one is in XAML, one can check whether there is text in a TextBox by using IsEmpty off of Text property.

Turns out that it bubbles down to CollectionView.IsEmpty (not on the string property) to provide the answer. This example of a textbox watermark, where two textboxes are displayed (on the editing one and one with the watermark text). Where the style on the second Textbox (watermark one) will bind to the Text on the main textbox and turn on/off accordingly.

<TextBox.Style>
    <Style TargetType="TextBox">
        <Style.Triggers>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding ElementName=tEnterTextTextBox, Path=IsKeyboardFocusWithin}" Value="False" />
                    <Condition Binding="{Binding ElementName=tEnterTextTextBox, Path=Text.IsEmpty}" Value="True" />
                </MultiDataTrigger.Conditions>
                <Setter Property="Visibility" Value="Visible" />
            </MultiDataTrigger>
            <DataTrigger Binding="{Binding ElementName=tEnterTextTextBox, Path=IsKeyboardFocusWithin}" Value="True">
                <Setter Property="Visibility" Value="Hidden" />
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=tEnterTextTextBox, Path=Text.IsEmpty}" Value="False">
                <Setter Property="Visibility" Value="Hidden" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBox.Style>

  • CollectionView.IsEmpty explanation
  • Help Text WaterMark to Disappear when user Types in (answer) (this is the full example which I used from the partial answer given above).

answered Jan 17, 2020 at 22:39

ΩmegaMan's user avatar

ΩmegaManΩmegaMan

29.2k10 gold badges99 silver badges121 bronze badges

You can put that code in the ButtonClick event or any event:

//Array for all or some of the TextBox on the Form
TextBox[] textBox = { txtFName, txtLName, txtBalance };

//foreach loop for check TextBox is empty
foreach (TextBox txt in textBox)
{
    if (string.IsNullOrWhiteSpace(txt.Text))
    {
        MessageBox.Show("The TextBox is empty!");
        break;
    }
}
return;

answered Jun 14, 2021 at 4:33

Shams Tech's user avatar

Another way:

    if(textBox1.TextLength == 0)
    {
       MessageBox.Show("The texbox is empty!");
    }

answered Apr 1, 2020 at 18:29

D J's user avatar

D JD J

8371 gold badge13 silver badges27 bronze badges

Here is a simple way

If(txtTextBox1.Text ==“”)
{
MessageBox.Show("The TextBox is empty!");
}

answered Nov 26, 2022 at 3:59

Aruna Prabhath's user avatar

Farhan answer is the best and I would like to add that if you need to fullfil both conditions adding the OR operator works, like this:

if (string.IsNullOrEmpty(text.Text) || string.IsNullOrWhiteSpace(text.Text))
{
  //Code
}

Note that there is a difference between using string and String

answered Nov 1, 2017 at 17:32

Roberto Torres's user avatar

5

In my opinion the easiest way to check if a textbox is empty + if there are only letters:

public bool isEmpty()
    {
        bool checkString = txtBox.Text.Any(char.IsDigit);

        if (txtBox.Text == string.Empty)
        {
            return false;
        }
        if (checkString == false)
        {
            return false;
        }
        return true;
    }

answered Aug 16, 2021 at 12:50

Guest28512's user avatar

1

aleksnice

Заблокирован

1

24.05.2012, 20:05. Показов 96540. Ответов 31


Студворк — интернет-сервис помощи студентам

Добрый всем день! Как можно делать, чтобы в таблицу не добавлялись значения если в textbox не введено значение?



0



Банальное исключение

127 / 95 / 12

Регистрация: 31.03.2010

Сообщений: 314

Записей в блоге: 1

24.05.2012, 20:12

2

Как вариант делать кнопку неактивной в событии text_changed, если textbox равен null. Или же при нажатии проверять, введено ли что-либо в textbox.



0



aleksnice

Заблокирован

24.05.2012, 20:23

 [ТС]

3

все равно добавляются значения в таблицу(( Мне нужно, если хоть в одном textbox пусто, в таблицу данные не заносились! Как это можно прописать?



0



WorldException

Банальное исключение

127 / 95 / 12

Регистрация: 31.03.2010

Сообщений: 314

Записей в блоге: 1

24.05.2012, 20:29

4

Например:

C#
1
2
3
4
if(textbox1.Text == "" || textbox2.Text == "")
{
    //Ничего не делаем
}

Добавлено через 31 секунду
aleksnice, Вы хоть код то покажите. Ну хоть немножко



2



aleksnice

Заблокирован

24.05.2012, 20:31

 [ТС]

5

А код «ничего не делаем» какой?) не проходит ничего на ум((

Добавлено через 1 минуту

C#
1
2
3
4
5
6
7
 private void textBoxFirstName_TextChanged(object sender, EventArgs e)
        {
            if (textBoxFirstName.Text != String.Empty)
            { 
                  
            }
        }

А в if не знаю что прописать(



1



WorldException

Банальное исключение

127 / 95 / 12

Регистрация: 31.03.2010

Сообщений: 314

Записей в блоге: 1

24.05.2012, 20:34

6

Цитата
Сообщение от aleksnice
Посмотреть сообщение

Мне нужно, если хоть в одном textbox пусто, в таблицу данные не заносились!

Цитата
Сообщение от aleksnice
Посмотреть сообщение

А код «ничего не делаем» какой?)

Намёк ясен?

Добавлено через 59 секунд
Например так:

C#
1
button1.Enabled = false;

Добавлено через 1 минуту
Иначе «true»

Добавлено через 27 секунд
А по нажатию на кнопку, например, данные заносятся в таблицу.



0



aleksnice

Заблокирован

24.05.2012, 20:36

 [ТС]

7

К сожалению эффекта никакого(((



0



Банальное исключение

127 / 95 / 12

Регистрация: 31.03.2010

Сообщений: 314

Записей в блоге: 1

24.05.2012, 20:37

8

Полностью код можно глянуть?



0



aleksnice

Заблокирован

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

Ну вот сразу бы так..
Пишем в событии по нажатию на кнопку:

C#
1
2
3
4
if(textbox1.Text == "" || textbox2.Text == "" || textbox3.Text == "")
{
    //Ничего не добавляем
}



0



aleksnice

Заблокирован

24.05.2012, 20:48

 [ТС]

11

А можете подсказать код «Ничего не добавляем» пожалуйста?)



0



Банальное исключение

127 / 95 / 12

Регистрация: 31.03.2010

Сообщений: 314

Записей в блоге: 1

24.05.2012, 20:57

12

Ну, оповестите пользователя о том, что нужно заполнить все поля для того, чтобы добавить данные в таблицу. С помощью MessageBox, например.



0



aleksnice

Заблокирован

24.05.2012, 21:01

 [ТС]

13

Это все понятно… но в таблицу данные заносятся!!!! А нужно, чтобы когда нажималась кнопка «Добавить» выскакивала окошка что поле ввода пусто и В ТАБЛИЦУ ДАННЫЕ НЕ ЗАНОСИЛИСЬ!!! т.е. чтобы кроме появления окошка ничего не появлялось!!



0



Банальное исключение

127 / 95 / 12

Регистрация: 31.03.2010

Сообщений: 314

Записей в блоге: 1

24.05.2012, 21:02

14

Покажите код на кнопке «Добавить»



0



aleksnice

Заблокирован

24.05.2012, 21:04

 [ТС]

15

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 if (textBoxFirstName.Text == "" || textBoxName.Text == "" || textBoxGroup.Text == "")
            {
               MessageBox.Show("пусто");
            }
 
            dataGridViewStudent.ColumnCount = 6;
            dataGridViewStudent.RowCount++;
            int row = dataGridViewStudent.RowCount - 1;
 
            /// Зажаем автоматическое подсчитывания списка
            try
            {
                dataGridViewStudent[0, row - 1].Value = int.Parse(dataGridViewStudent[0, row - 2].Value.ToString()) + 1;
            }
            catch { dataGridViewStudent[0, row - 1].Value = 1; };
            ///Считываем все вносимые данные, которые заносятся в различне TextBox
            ///Переносим все внесенные данные в таблицу dataGridViewStudent, пи помощи кнопки "Добавить"
            dataGridViewStudent[1, row - 1].Value = textBoxFirstName.Text;
            dataGridViewStudent[2, row - 1].Value = textBoxName.Text;
            dataGridViewStudent[3, row - 1].Value = dateTimePickerGod.Text;
            dataGridViewStudent[4, row - 1].Value = textBoxGroup.Text;
            // Очищаем все TextBox, от ранее занесенных данных
            ClearField();

Вот весь код на кнопки ДОБАВИТЬ)



0



WorldException

Банальное исключение

127 / 95 / 12

Регистрация: 31.03.2010

Сообщений: 314

Записей в блоге: 1

24.05.2012, 21:07

16

Вы вот так попробуйте…

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
if (textBoxFirstName.Text == "" || textBoxName.Text == "" || textBoxGroup.Text == "")
{
    MessageBox.Show("пусто");
}
else
{
    dataGridViewStudent.ColumnCount = 6;
    dataGridViewStudent.RowCount++;
    int row = dataGridViewStudent.RowCount - 1;
 
    /// Зажаем автоматическое подсчитывания списка
    try
    {
        dataGridViewStudent[0, row - 1].Value = int.Parse(dataGridViewStudent[0, row - 2].Value.ToString()) + 1;
    }
    catch { dataGridViewStudent[0, row - 1].Value = 1; };
    ///Считываем все вносимые данные, которые заносятся в различне TextBox
    ///Переносим все внесенные данные в таблицу dataGridViewStudent, пи помощи кнопки "Добавить"
    dataGridViewStudent[1, row - 1].Value = textBoxFirstName.Text;
    dataGridViewStudent[2, row - 1].Value = textBoxName.Text;
    dataGridViewStudent[3, row - 1].Value = dateTimePickerGod.Text;
    dataGridViewStudent[4, row - 1].Value = textBoxGroup.Text;
    // Очищаем все TextBox, от ранее занесенных данных
    ClearField();
}



1



aleksnice

Заблокирован

24.05.2012, 21:11

 [ТС]

17

Все гениально просто… Спасибо все заработало

Добавлено через 1 минуту
А вы случайно не знаете, как можно сделать, чтобы в TextBoxe слово начиналось с большой буквы, т.е. заглавной??



0



Банальное исключение

127 / 95 / 12

Регистрация: 31.03.2010

Сообщений: 314

Записей в блоге: 1

24.05.2012, 21:11

18

Всегда пожалуйста.



2



aleksnice

Заблокирован

24.05.2012, 21:15

 [ТС]

19

А вы случайно не знаете, как можно сделать, чтобы в TextBoxe слово начиналось с большой буквы, т.е. заглавной??



0



Pooh

407 / 359 / 82

Регистрация: 07.10.2009

Сообщений: 558

25.05.2012, 13:36

20

Цитата
Сообщение от aleksnice
Посмотреть сообщение

как можно сделать, чтобы в TextBoxe слово начиналось с большой буквы

C#
1
2
3
4
5
6
7
8
void TextBox1TextChanged(object sender, EventArgs e)
{
    if(textBox1.Text.Length == 1)
    {
        textBox1.Text = textBox1.Text.ToUpper();
        textBox1.SelectionStart = textBox1.Text.Length;
    }
}

По-моему, так!



4



I am trying to validate textboxes for empty values. If the textbox is empty and loses focus, an error has to show and the textbox has to receive focus again.

Reading about this I came across the Validating event, which can be cancelled through e.Cancel. However when I try to do this, I get an error message.

My code:

private void CheckInput(CancelEventArgs e, TextBox tb)
{
   ErrorProvider error = new ErrorProvider();
   if (!string.IsNullOrEmpty(tb.Text))
   {
      error.SetError(tb, "*");
      e.Cancel = true;
   }

   else
   {
      error.SetError(tb, "");
   }
}

private void tbTitel_Validated(object sender, CancelEventArgs e)
{
    CheckInput(e, tbTitel);

}

And the error I get is the following:

Error 1 No overload for ‘tbTitel_Validated’ matches delegate ‘System.EventHandler’

How can I fix this?

Neel Bhasin's user avatar

Neel Bhasin

7491 gold badge7 silver badges22 bronze badges

asked Jan 10, 2014 at 8:50

Matthijs's user avatar

The validating uses this delegate:

private void tbTitel_Validating(object sender, CancelEventArgs e)
{
}

The validated event uses this:

private void tbTitel_Validated(object sender, EventArgs e)
{
}  

You want to use the Validating event (you should link you eventhandler to the validating event, not the validated event. This way you can cancel it.

You probably clicked the validating first and copy/paste/selected the eventhandler name into the validated event. (designer)

Yves Schelpe's user avatar

Yves Schelpe

3,3044 gold badges36 silver badges69 bronze badges

answered Jan 10, 2014 at 8:58

Jeroen van Langen's user avatar

You should use the Validating event to execute your checks, not the Validated event.

The two events have different signatures. The Validated event receives the simple EventArgs argument, while the Validating event receives the CancelEventArgs argument that could be used to revert the focus switch.

Said that, it seems that your logic is wrong.

// error if string is null or empty
// if (!string.IsNullOrEmpty(tb.Text))
if (string.IsNullOrEmpty(tb.Text))
{
   error.SetError(tb, "*");
   e.Cancel = true;
}
else
{
   error.SetError(tb, "");
}

answered Jan 10, 2014 at 8:54

Steve's user avatar

SteveSteve

213k22 gold badges232 silver badges286 bronze badges

1

Alwasy use validation statements at Object.Validated event handler

Likewise:


 private void textBox1_Validated(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text) || textBox1.Text == "")
            {
                MessageBox.Show("Please use valid data input!!");
            }
        }

answered Oct 17, 2014 at 20:13

Ashraf Sada's user avatar

Ashraf SadaAshraf Sada

4,4692 gold badges44 silver badges48 bronze badges

  1. HowTo
  2. C# Howtos
  3. Check if TextBox Is Empty in C#

Muhammad Maisam Abbas
Jan 30, 2023
Apr 11, 2021

  1. Check if a TextBox Is Empty With the String.IsNullOrEmpty() Function in C#
  2. Check if a TextBox Is Empty With the TextBox.Text.Length Property in C#

Check if TextBox Is Empty in C#

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:

C# check textbox is empty - 1

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:

C# check textbox is empty - 1

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.

Muhammad Maisam Abbas avatar
Muhammad Maisam Abbas avatar

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.

LinkedIn

Related Article — Csharp GUI

  • Save File Dialog in C#
  • Group the Radio Buttons in C#
  • Add Right Click Menu to an Item in C#
  • Add Items in C# ComboBox
  • Add Placeholder to a Textbox in C#
  • Simulate a Key Press in C#
  • 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

  • Если счетная ошибка как удержать у сотрудника
  • Если судебный эксперт допустил ошибку
  • Если стиральная машинка выдает ошибку н20
  • Если стиральная машинка выдает ошибку f05
  • Если стиральная машина самсунг выдает ошибку ue