If else statement textbox error - c#

I am trying to create an if else statement to show a message box if no input.
If(textbox1.text==false)
{
messagebox.show("please fill in the boxes")
}
I have 16 different text box currently out, do i need to use an if else statement for each?

Pass all TextBoxes in the list and loop it
//Create list once in the constructor of main form or window
List<TextBox> list = new List<TextBox>()
//...
list.Add(textbox1);
list.Add(textbox2);'
//...
Then loop it
foreach(TextBox txt in list)
{
if(String.IsNullOrWhiteSpace(txt.Text))
{
messagebox.Show("please fill in the boxes");
break;
}
}
Update
If all textboxes expecting only number/double input then use TryParse for checking if value is valid
foreach(TextBox txt in list)
{
Double temp;
if(Double.TryParse(txt.Text, temp) == true)
{
//save or use valid value
Debug.Print(temp.ToString());
}
else
{
messagebox.Show("please fill in the boxes");
break;
}
}

You can not compare string with Boolean. textbox.text is a string data type.
try this, if you want to show different message for different textbox, you must use if-else statement for all texboxes.
If(textbox1.text=="")
{
messagebox.show("please fill in the boxes")
}
or
If(string.IsNullOrEmpty(textbox1.text) == true)
{
messagebox.show("please fill in the boxes")
}
for multiple textbox validation
Adding the handler to the textboxes is easily done with a foreach loop in the form constructor:
foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
tb.Validating += textBox_Validating;
}
use validating event to handle it
private void textBox_Validating(object sender, CancelEventArgs e)
{
TextBox currenttb = (TextBox)sender;
if(currenttb.Text == "")
MessageBox.Show(string.Format("Empty field {0 }",currenttb.Name.Substring(3)));
e.Cancel = true;
else
{
e.Cancel = false;
}
}

String and Boolean aren't comparable, also you can check if all the textfields are empty like described in this post
if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)) {
//Textfield is empty
}

First of all, you have a type mismatch error in your question. The Text property of a TextBox is of string type, while the keyword false is of bool type. You can read more on types in here.
The fix to this issue would be:
If (!string.IsNullOrEmpty(textbox1.Text))
{
Messagebox.Show("please fill in the boxes")
}
Secondly, modern programming is all about DRY principle. So, the answer is no, you do not need to write the same piece of code for each of them.
You could actually do it at least two ways.
The first way would be to create some sort of collection of your textboxes (an array, for example). Then you would create a method to iterate over this collection like this:
private bool AllTextboxesAreFilled()
{
var textboxes = new TextBox[] { textBox1, textBox2, textBox3 };
return textboxes.All(textbox => !string.IsNullOrEmpty(textbox.Text));
}
And then call it like:
if (!AllTextboxesAreFilled())
{
MessageBox.Show("please fill in the boxes");
}
The second way would be to make these textboxes children of some control (a Panel, for example) and then iterate over these children. This way you don't need to create an additional collection (and to remember to add elements in it in case you need more textboxes):
private bool AllTextboxesAreFilled()
{
return holderPanel.Controls.OfType<TextBox>().All(textbox => !string.IsNullOrEmpty(textbox.Text));
}
The usage is the same as in the previous example.

Related

WinForms (C#) input field with database-driven autocomplete

I am trying to create a text input field with autocomplete functionality. The list of available options is huge (50,000+) and will need to be queried on TextChanged (after the first 3 characters have been entered).
I have a 99%-working solution with TextBox, setting AutoCompleteCustomSource to my new AutoCompleteStringCollection in the TextChanged event, but that results in occasional memory access violations due to a well-documented bug in the underlying AutoComplete implementation...
Microsoft Support say "Do not modify the AutoComplete candidate list dynamically during key events"...
Several SO threads: 1, 2, 3
These threads have some suggestions on how to prevent the exceptions but nothing seems to completely eliminate them, so I'm looking for an alternative. have tried switching to a ComboBox-based solution but can't get it to behave as I want.
After the user types the third character, I update the ComboBox's DataSource but the first item is automatically selected. The user is not able to continue typing the rest of the name.
The ComboBox items are not visible until the user clicks the triangle to expand the list
If the user selects the text they have entered and starts typing, I set DataSource to null to remove the list of suggestions. Doing this puts the cursor at the start of the text, so their characters appear in completely the wrong order!
My View:
public event EventHandler SearchTextChanged;
public event EventHandler InstrumentSelected;
public Instrument CurrentInstrument
{
get { return comboBoxQuickSearch.SelectedItem as Instrument; }
}
public IEnumerable<Instrument> Suggestions
{
get { return comboBoxQuickSearch.DataSource as IEnumerable<Instrument>; }
set
{
comboBoxQuickSearch.DataSource = value;
comboBoxQuickSearch.DisplayMember = "Name";
}
}
public string SearchText
{
get { return comboBoxQuickSearch.Text; }
}
private void comboBoxQuickSearch_TextChanged(object sender, EventArgs e)
{
if (SearchTextChanged != null)
{
SearchTextChanged(sender, e);
}
}
private void comboBoxQuickSearch_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && InstrumentSelected != null)
{
InstrumentSelected(sender, e);
}
}
My Presenter:
private void SearchTextChanged(object sender, EventArgs e)
{
lock (searchLock)
{
// Do not update list of suggestions if:
// 1) an instrument has already been selected
// (the user may be scrolling through suggestion list)
// 2) a search has taken place within the last MIN_SEARCH_INTERVAL
if (DateTime.Now - quickSearchTimeStamp < minimumSearchInterval
|| (view.Suggestions != null && view.Suggestions.Any(i => i.Name == view.SearchText)))
{
return;
}
string searchText = view.SearchText.Trim();
if (searchText.Length < SEARCH_PREFIX_LENGTH)
{
// Do not show suggestions
view.Suggestions = null;
searchAgain = false;
}
// If the prefix has been entered or changed,
// or another search is needed to display the full sublist
else if (searchText.Length == SEARCH_PREFIX_LENGTH
|| searchText.Substring(0, SEARCH_PREFIX_LENGTH) != searchTextPrefix
|| searchAgain)
{
// Record the current time and prefix
quickSearchTimeStamp = DateTime.Now;
searchTextPrefix = searchText.Substring(0, SEARCH_PREFIX_LENGTH);
// Query matches from DB
IList<Instrument> matches = QueryMatches(searchText);
// Update suggestions
view.Suggestions = matches;
// If a large number of results was received, search again on the next chararacter
// This ensures the full match list is presented
searchAgain = matches.Count() > MAX_RESULTS;
}
}
}
(The searchAgain bit is left over from the TextBox implementation, where the AutoCompleteCustomSource wouldn't always show the complete list if it contained too many items.)
Can I get the ComboBox to work as I want it to, providing suggestions as the user types, given my requirement to query those suggestions on TextChanged?
Is there some other combination of controls I should use for a better user experience, e.g. ListBox?

Finding which textbox is empty

I have short windows program I use to add information quickly. But now I'm trying to enhance it.
Was looking for a more efficient want to check for empty text boxes and if the box was empty to find which one it was and set the focus back to only that box. Currently I loop through all of them and check to see if any box was empty if it is just display a message. But have to look to see which box is missing text. Heres the code:
bool txtCompleted = true;
string errorMessage = "One or more items were missing from the form";
foreach(Control c in Controls)
{
if (c is TextBox)
{
if (String.IsNullOrEmpty(c.Text))
{
txtCompleted = false;
}
}
}
if (txtCompleted == false)
{
MessageBox.Show(errorMessage);
}
Your approach using foreach looks promising to me. Howver you can use LINQ as well
if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)) {
...
}
You can use the focus() method to set the focus to the empty text box.
Set the focus on the control while in your loop, then break when done.
foreach(Control c in Controls)
{
if (c is TextBox)
{
if (String.IsNullOrEmpty(c.Text))
{
txtCompleted = false;
c.Focus();
MessageBox.Show(errorMessage);
break;
}
}
}
To get a reference to the empty textbox you use almost the same solution as R.T. presents, but use FirstOrDefault instead:
var emptyTextBox = Controls.OfType<TextBox>().FirstOrDefault(t => string.IsNullOrEmpty(t.Text)
if (emptyTextBox != null)
{
// there is a textbox that has no Text set
// set focus, present error message etc. on emptyTextBox
}

How could I check if a textbox has text?

I'm trying to make an if statement to check whether a TextBox has text it.
So something like this:
if (textbox1 has text)
{
//Then do this..
}
How would I write "textbox1 has text"?
if (textbox1.Text.Length > 0)
{
...
}
or
if (!string.IsNullOrEmpty(textbox1.Text))
{
...
}
You can get the text stored in the TextBox using Text property of the TextBox and then check whether it is null or empty like this :-
string text = textBox1.Text ;
if(String.IsNullOrEmpty(text))
{
// Do something
}
Check the length of the text box text.
if (textbox1.Text.Length > 0)
{
//do the process here
}
Please try
if(!string.IsNullOrWhiteSpace(textbox1.Text))
{
//
}
Checking the Length
if (textBox1.Text.Length > 0)
{
// perform task
}
Using the Null
if (!string.IsNullOrEmpty(textBox1.Text))
{
// perform a task
}
Using Trim would be nice for checking if a user is only putting spaces.
if (textBox1.Text.Trim().Length > 0)
{
// perform a task
}
Try any one of these and it should work. There are way more ways but since this question is a bit broad it's up to you.
Simple. Check out this MSDN page: string.IsNullOrEmpty
if (!string.IsNullOrEmpty(textBox1.Text))
{
}
Alternatively, you could use a property. This is especially helpful when you need to check multiple times to see if the textbox has text:
// a public property is not necessary for this
bool HasText
{
get
{
return !string.IsNullOrEmpty(textBox1.Text);
}
}
...
if (HasText)
{
}
Another way to go about doing this is by using an extension method:
public static class TextBoxUtility
{
public static bool HasText(this TextBox textBox)
{
return !string.IsNullOrEmpty(textBox.Text);
}
}
...
if(textBox1.HasText())
{
}
I prefer the latter instead of a property because it works across all textboxes.
the simpliest logic is this:
if (textBox1.Text != "")
MessageBox.Show("The textbox is not empty!");
else
MessageBox.Show("The textbox is empty!");
I have seen all the other answers on the page, suggesting solutions like
if (tb.Text == "")
{
// Is empty
} else {
// Is not empty
}
However this could easily break, and return that a text box is not empty, when it actually is. For example, a few spaces in the text box (and nothing else) would pass as not empty, when in fact, while not technically empty, you would probably want to report it as empty. A solution to this is the C# string.Trim() method. This removed all whitespace. Now changing my solution to this:
if (tb.Text.Trim() == "")
{
// Is empty
} else {
// Is not empty
}
... it would no longer report a text box full with spaces as not empty.
if(textBox1.Text!=null)
{
///code
}
or
if(textBox1.Text!=string.Empty)
{
//code
}
if(textbox.Text.Trim().Length > 0)
{
// Do something
}

Text from textboxes to list

I'm REALLY new to C# and programming overall, so my question might be stupid in your opinion but here it is.
I have created a form which contains 7 textboxes and i want to collect text from these textboxes and add them to a list. I however get an error saying, System.Windows.Forms.TextBox is a 'type' but is used like a 'variable". What should I do?
for (int i = 1; i < 8; i++)
{
if (TextBox[i].Text == "")
{
days.Add("Restday");
}
else
{
days.Add(TextBox[i].Text);
}
}
TextBox is a type. so TextBox[i] is causing you trouble.
You can alway do something like this
foreach(Control ctrl in yourform.Controls)
{
Textbox = ctrl as TextBox;
if(txtBox != null)
{
if (txtBox.Text == "")
{
days.Add("Restday");
}
else
{
days.Add(txtBox.Text);
}
}
}
This work for a basic form. If you have pannel and other container to organize your controls the approch described in Guffa answer might be better. This could also be rewritten as method who accept a collection of Control recursive use to reach all controls.
Put the textbox references in an array so that you can easily loop through them. If your textboxes are named TextBox1 to TextBox7:
TextBox[] boxes = {
TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6, TextBox7
};
foreach (TextBox box in boxes) {
if (box.Text == "") {
days.Add("Restday");
} else {
days.Add(box.Text);
}
}
I guess you don't have an array named TextBox that is why the error. You can try following:
List<strig> days = this.Controls.OfType<TextBox>
.Select(r=> string.IsNullOrWhiteSpace(r.Text)
? "Restday" : r.Text)
.ToList();
But the above would give you the textboxes added on the form directly, If these textboxes are inside other control then you can look for recursively
Go into the form editor and select one of your textboxes. Now find the properties window. If it's not visible then click View->Properties Window
One of the properties in there will be the name of the textbox control. Use that to access it's text value like so:
days.Add(txtMyTextboxName.Text);
If you must iterate through the textboxes you can do this:
foreach(var Textbox in this.Controls.OfType<TextBox>())
{
if (Textbox.Text == "")
{
days.Add("Restday");
}
else
{
days.Add(Textbox.Text);
}
}
But bear in mind this is a pretty non-standard approach and not recommended.

How can I check multiple textboxes if null or empty without a unique test for each?

I have about 20 text fields on a form that a user can fill out. I want to prompt the user to consider saving if they have anything typed into any of the text boxes. Right now the test for that is really long and messy:
if(string.IsNullOrEmpty(txtbxAfterPic.Text) || string.IsNullOrEmpty(txtbxBeforePic.Text) ||
string.IsNullOrEmpty(splitContainer1.Panel2) ||...//many more tests
Is there a way I could use something like an Array of any, where the array is made of the text boxes and I check it that way? What other ways might be a very convenient way in which to see if any changes have been made since the program started?
One other thing I should mention is there is a date time picker. I don't know if I need to test around that as the datetimepicker will never be null or empty.
EDIT:
I incorporated the answers into my program, but I can't seem to make it work correctly.
I set up the tests as below and keep triggering the Application.Exit() call.
//it starts out saying everything is empty
bool allfieldsempty = true;
foreach(Control c in this.Controls)
{
//checks if its a textbox, and if it is, is it null or empty
if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))
{
//this means soemthing was in a box
allfieldsempty = false;
break;
}
}
if (allfieldsempty == false)
{
MessageBox.Show("Consider saving.");
}
else //this means nothings new in the form so we can close it
{
Application.Exit();
}
Why is it not finding any text in my text boxes based on the code above?
Sure -- enumerate through your controls looking for text boxes:
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text == string.Empty)
{
// Text box is empty.
// You COULD store information about this textbox is it's tag.
}
}
}
Building on George's answer, but making use of some handy LINQ methods:
if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))
{
//Your textbox is empty
}
public void YourFunction(object sender, EventArgs e) {
string[] txtBoxArr = { textBoxOne.Text, textBoxTwo.Text, textBoxThree.Text };
string[] lblBoxArr = { "textBoxOneLabel", "textBoxTwoLabel", "textBoxThreeLabel" };
TextBox[] arr = { textBoxOne, textBoxTwo, textBoxThree };
for (int i = 0; i < txtBoxArr.Length; i++)
{
if (string.IsNullOrWhiteSpace(txtBoxArr[i]))
{
MessageBox.Show(lblBoxArr[i] + " cannot be empty.");
arr[i].Focus();
return;
}
}
}

Categories