I'm building a search program that connect to SQL database using Windows form and C#.
If no value is input into any textbox then message box would pop up "Please Input a Value". My code works but how can I make it cleaner?
I have multiple search boxes but I want to prevent user from searching if they put value in multiple textboxes simultaneously. Example: if customer input "1" into textBox1 and "V" into textBox2, then message box would pop up display "Can Only Search From One Textbox", when pressing search button.
Thanks for your help!
if (textBox1.Text == string.Empty && textBox2.Text == string.Empty &&
textBox3.Text == string.Empty && textBox4.Text == string.Empty && textBox5.Text
== string.Empty && textBox6.Text == string.Empty && textBox7.Text ==
string.Empty && textBox8.Text == string.Empty && textBox9.Text == string.Empty
&& textBox10.Text == string.Empt && textBox11.Text == string.Empty && textBox12.Text == string.Empty)
{
MessageBox.Show("Please Input a Value");
}
if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0 && textBox7.Text.Length > 0)
{
MessageBox.Show("Can Only Search From One Textbox");
}
答案 0 :(得分:1)
Consider LINQ
You could take advantage of LINQ to query all of your TextBox elements at the same time via the Cast()
and All()
methods :
// Are all TextBox Controls empty?
var allEmpty = Controls.Cast<TextBox>().All(t => String.IsNullOrWhiteSpace(t.Text));
// Handle accordingly
if(allEmpty)
{
MessageBox.Show("Please Input a Value");
}
Likewise, you could use the same basic logic to check if multiple elements have content using the Count()
method to see how many controls satisfy your requirement :
// Is more than one non-empty?
var multipleWithContent = Controls.Cast<TextBox>().Count(t => String.IsNullOrWhiteSpace(t.Text)) > 1;
// Handle accordingly
if(multipleWithContent)
{
MessageBox.Show("Can Only Search From One Textbox");
}
If you wanted to "scope" these, you could consider placing all of the TextBox controls that you wanted to check within a parent control and using the same basic approach (i.e. YourParentControl.Controls.Cast<TextBox>()...
) to only grab the TextBox elements within that specific control.
答案 1 :(得分:0)
These answers are variations of this answer: https://stackoverflow.com/a/8750334/6535105
1) The goal here is to check if all textboxes are empty.
if(this.Controls.OfType<TextBox>().All(t => string.IsNullOrEmpty(t.Text)) {
...
}
2) The goal is to ensure that only one textbox has text in it. This if statement should handle that:
if(this.Controls.OfType<TextBox>().Where(t => !string.IsNullOrEmpty(t.Text)).Count() > 1) {
...
}
The LINQ statement gets all textboxes that are not empty and counts the number of them that exist. The if statement is true if that number is greater than 1 (multiple textboxes have text in them).
Disclaimer: I have not tested any of this code.