To answer exactly the question title, Shorter, clearer:
button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
Вопрос
I just started learning C#.
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
object Nappi1 = ("Nice button");
MessageBox.Show(Nappi1.ToString());
}
I got a textbox, that should disable the button1
if empty or whitespace.
I already got it working in some level, but it checks the state of the textbox
on button1_Click
.
private void button1_Click(object sender, EventArgs e)
{
if (textBox1 = "")
{
button1.enabled = false;
}
else
{
button1.enabled = true;
object Nappi1 = ("Nice button");
MessageBox.Show(Nappi1.ToString());
}
}
Fictional example:
if (textBox1 = "" or textBox1 = whitespace[s])
textbox
onLoad
(as soon as the program starts)?whitespace
, and can I write it to the same if
-statement?Please keep it simple.
Решение
To answer exactly the question title, Shorter, clearer:
button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
Другие советы
Replace your if-else with this, if it is only a string
:
if (string.IsNullOrWhiteSpace(textBox1)) {
button1.enabled = false;
}
else {
button1.enabled = true;
...
}
or use textBox1.Text
if it is really a Textbox
use this:
if (string.IsNullOrWhiteSpace(textBox1.Text)) {
button1.enabled = false;
}
else {
button1.enabled = true;
...
}
You want String.IsNullOrWhiteSpace
:
if (String.IsNullOrWhiteSpace(textBox1.Text)) {
button1.enabled = false;
}
You originally had:
if (textBox1 = "") {
button1.enabled = false;
}
textbox
is the control, you need to use the Text
property which refers to the string literal inside the textbox control. Also in C# =
is an assignment, you ideally would want ==
which is used to compare.
If you're not using .NET 4
or .NET 4.5
you can use:
This can be done by using hooking an event handler to text-box text changed event. Steps:
Attach an event handler for text-box (on text changed) Inside the text changed event handler enable / disable the button.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text))
button1.Enabled = false;
else
button1.Enabled = true;
}
By default disable the button in InitializeComponent method of form
button1.Enabled = false;
In the textBox1 text changed event, right this code:
button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
string.IsNullOrWhiteSpace("some text") will check if the text is none or just a wightspaces if this is true you will set button1.Enabled to false.