How to request form input in C # if it is empty?
2 answers
This can be done in different ways.
The simplest. This is essentially what Egor has already proposed. We place the Label next to our textbox. Sign the textbox on the TextChanged event, write the following code in it:
private void TextBox1_TextChanged(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textBox1.Text)) label.Text = "Введите значение"; else label.Text = ""; } Without the use of an additional label. We sign our TextBox on two events: Enter and Leave .
private void textBox2_Enter(object sender, EventArgs e) { if (textBox2.Text == "Введите значение") { textBox2.Text = ""; textBox2.ForeColor = SystemColors.WindowText; } } private void textBox2_Leave(object sender, EventArgs e) { if (textBox2.Text.Trim() == "") { textBox2.Text = "Введите значение"; textBox2.ForeColor = SystemColors.GrayText; } } Create a descendant class in which we send a special message using the WinAPI function SendMessage . As a result, when the TextBox empty and out of focus, it will display a watermark.
class WatermarkedTextBox : TextBox { [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wp, string lp); protected override void OnHandleCreated(EventArgs e) { const uint msg = 0x1501; base.OnHandleCreated(e); if (IsHandleCreated) { SendMessage(Handle, msg, IntPtr.Zero, "Введите значение"); } } } Another way is to use the ErrorProvider class.
Add this component to the form. Give it the desired property values ( BlinkStyle ). Subscribe the TextBox to the event Validating . Write the code in it:
private void textBox3_Validating(object sender, CancelEventArgs e) { if (textBox3.Text.Trim() == "") errorProvider1.SetError(textBox3, "Введите значение"); else errorProvider1.SetError(textBox3, ""); } As a result, when this textbox loses focus, validation will occur. If no value is entered, a red error provider icon will appear next to it. When you mouse over it, ToolTip will appear with the text of the error.
In principle, you can combine ErrorProvider with one of the other methods.
if(TextBox.Text == "") { Label1.Text = "Поле TextBox должно быть заполнено"; return; } It is necessary to add a label in the form, which will be empty (without text)
In general, describe in more detail what you need. Where do you want to display the message?
- I agree, I didn’t finish it. I want to display a message in the same form, for example, enter a number and read it. - Nikita
- @Nikita Where to withdraw? In the label? In the new window? - Egor Trutnev
- @Nikita by writing a "form", do you mean a new window (as with an error)? Post of this type - Egor Trutnev
- No, by form, I mean textbox. - Nikita
- oneFor the question: "Where are you doing?" sorry! It is logical, because there is no TextBox in the console - Egor Trutnev