I'm trying to create textbox where you can enter your name.
If textbox is empty show error.
If textbox contain numbers show error.
In my sample it does show error when i have empty textbox and when i have numbers like Robert1. But it does not work when Text ends with a letter. If you write 1Robert, then it doesn't show error.
My code:
string vards = textBox1.Text;
// Empty or wrong format
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
label5.Text = "You didn't enter anything!";
}
else
{
foreach(char c in vards)
{
if (Char.IsNumber(c))
{
label5.Text = "Your name is incorrect!";
}
else
{
label5.Text = "";
}
}
}
I guess i just had to add break;
if (Char.IsNumber(c))
{
label5.Text = "Your name is incorrect!";
break;
}
the loop produces a invalid result. it overwrites the content of label5 each char of label1 and the final result is only about the last char
// Empty or wrong format
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
label5.Text = "You didn't enter anything!";
}
else
{
bool onlyLetters = textBox1.Text.All(x => Char.IsLetter(x));
if (!onlyLetters)
{
label5.Text = "Your name is incorrect!";
}
else
{
label5.Text = "";
}
}
You are using a loop on every character in the text. There you are overwriting label5.Text always. So actually only the last character matters in your logic.
You can use this:
bool anyNumbers = textBox1.Text.Any(Char.IsDigit);
if(anyNumbers)
{
label5.Text = "Your name is incorrect!";
}
Here without LINQ:
bool valid = true;
foreach (char c in textBox1.Text)
{
if (char.IsDigit(c))
{
valid = false;
break;
}
}
You could do the following:
var input = txtExample.Text;
if(!string.IsNullOrEmpty(input))
if(input.Any(d => char.IsDigit(d) == false)
{
// Valid
}
You could actually use Linq, not even use the foreach loop. Keep in mind this is being done on the server side, if your in a web application you trigger a PostBack. Which you may want to do that, so if it is web based, you should do it Client Side.
Related
I'm attempting to pass the name of 2 textboxes into a method so that it edits the text in them. I have tried looking for examples online but can only find people attempting to pass textbox text through.
I've tried passing it in by declaring the text boxes in the method constructor.
MethodName(string text, tb_1, tb_2);
private void MethodName(string str, TextBox tb_name, TextBox tb_allergen)
{
string ingredientName = "";
string ingredientAllergen = "";
//code to change strings//
tb_name.Text = ingredientName;
tb_allergen.Text = ingredientAllergen;
}
After running the code I expect the text box text to be changed to the appropriate value, instead I get this error about the textboxes in the call.
"An unhandled exception of type 'System.InvalidCastException' occurred in mscorlib.dll
Additional information: Unable to cast object of type 'System.Windows.Forms.TextBox' to type 'System.IConvertible'"
Really sorry if there's an easy fix for this, but please point me in the right direction. Thanks in advance.
Real Code
ingredientDBAccess ingredientDBA = new ingredientDBAccess(db);
populateBoxesWithIngredientResults( ingredientDBA.getIngredientsFromID(Convert.ToInt32(tb_viewIngredient1)), tb_viewIngredient1, tb_viewAllergen1);
private void populateBoxesWithIngredientResults(List<ingredient> ingredientList, TextBox tb_name, TextBox tb_allergen)
{
string ingredientName = "";
string ingredientAllergen = "";
foreach (ingredient ingredient in ingredientList)
{
string name = Convert.ToString(ingredient.IngredientName);
ingredientName = name;
string allergen = "N/A";
switch (ingredient.AllergenID)
{
case 0:
allergen = "N/A";
break;
case 1:
allergen = "Nut";
break;
case 2:
allergen = "Gluten";
break;
case 3:
allergen = "Dairy";
break;
case 4:
allergen = "Egg";
break;
}
ingredientAllergen = allergen;
}
tb_name.Text = ingredientName;
tb_allergen.Text = ingredientAllergen;
}
Yes it is possible:
void MyMethod(string str, TextBox txt)
{
txt.Text = str + " some text from the method itself";
}
You may even return a TextBox:
TextBox MyFunc(string str)
{
TextBox txt = new TextBox();
txt.Text = str;
return txt;
}
You are trying to convert TextBox into Int32:
Convert.ToInt32(tb_viewIngredient1)
which is not parsable to Int32. You may convert it's text to int32 (if it has a numeric value and can be parsed) like:
int.Parse(tb_viewIngredient1.Text)
or
Conver.ToInt32(tb_viewIngredient1.Text)
The problem is the in two places
MethodName(string theStringVariable, tb_1, tb_2);
private void MethodName(string theStringVariable, TextBox tb_name, TextBox tb_allergen)
{
Convert.ToInt32(tb_viewIngredient1) will throw an exception because you're trying to convert a TextBox control to an int. Instead, try passing the Text property of the TextBox to the method:
Convert.ToInt32(tb_viewIngredient1.Text)
The problem is in (Convert.ToInt32(tb_viewIngredient1), you must convert it to:
(Convert.ToInt32(tb_viewIngredient1.Text)
I see three different options here. Any of these would be better even than the fixed code, depending on what your needs are. All of them address two points:
You can use a lookup table for the allergens rather than a switch. The resulting code is shorter/simpler and should run faster.
You loop through every item in ingredientList, but the textboxes will only ever keep data from the last item in the list. Either look at just that last item (no need for a loop), or use all of the items in the list (ie: create csv strings). The loop as it is is wasteful and complicates the code.
.
private void populateBoxesWithIngredientResults(IEnumerable<ingredient> ingredientList, TextBox tb_name, TextBox tb_allergen)
{
string nameDelimiter = "";
string allergenDelimiter = "";
string ingredients = "";
string allergens = "";
var allergenTable = {"N/A", "Nut", "Gluten", "Dairy", "Egg"};
foreach (ingredient ingredient in ingredientList)
{
//Is Convert.ToString() really needed here?
// I feel like ingredient.IngredientName is ALREADY A STRING
ingredients += delimiter + Convert.ToString(ingredient.IngredientName);
nameDelimiter = ",";
if (ingredient.AllergenID > 0 && ingredient.AllergenID < allergenTable.Length)
{
allergens += allergenDelimiter + allergenTable[ingredient.AllergenID];
allergenDelimiter = ",";
}
}
if (allergens == "") allergens = "N/A";
tb_name.Text = ingredients;
tb_allergen.Text = allergens;
}
or
private void populateBoxesWithIngredientResults(IEnumerable<ingredient> ingredientList, TextBox tb_name, TextBox tb_allergen)
{
tb_name.Text = string.Join(",", ingredientList.Select(i => i.IngredientName));
var allergenTable = {"N/A", "Nut", "Gluten", "Dairy", "Egg"};
var allergens = ingredientList.
Select(i => (i.AllergenID > 0 && i.AllergenID < allergenTable.Length)? allergenTable[i.AllergenID]):"").
Where(i => i.Length > 0);
var result = string.Join(",", allergens);
if (string.IsNullOrEmpty(result)) result = "N/A";
tb_allergen.Text = result;
}
or
private void populateBoxesWithIngredientResults(List<ingredient> ingredientList, TextBox tb_name, TextBox tb_allergen)
{
if (ingredientList.Length == 0)
{
tb_name.Text = "";
tb_allergen.Text = "";
}
var allergenTable = {"N/A", "Nut", "Gluten", "Dairy", "Egg"};
var ingredient = ingredientList[ingredientList.Count - 1];
tb_name.Text = ingredient.IngredientName;
if (ingredient.AllergenID >= 0 && ingredient.AllergenID < allergenTable.Length)
{
tb_allergen.Text = allergenTable[ingredient.AllergenID];
}
else
{
tb_allergen.Text = "N/A";
}
}
This is my code
public void showMatch (string guess, string regx){
int outputCode;
MatchCollection mc = Regex.Matches (guess, regx);
foreach (Match m in mc) {
listOfTags [ctr] = m.Value;
ctr++;
}
checkOpeningTag = listOfTags [0];
checkClosingTag = listOfTags [1];
if (checkOpeningTag.Equals ("<h1>")) {
if (checkClosingTag.Equals ("</h1>")) {
outputCode = 3;
} else {
outputCode = 2;
}
} else {
outputCode = 1;
}
showError(outputCode);
}
public void showError(int checkError){
if (checkError == 1) {
error.text = "Sorry, no opening tag found.";
} else if(checkError == 2){
error.text = "Sorry, no closing tag found.";
}else if(checkError == 3){
error.text = "You got it right! Advancing to next level!";
}
}
If I try to input <'h1'> and <'h1'> (disregard ') , it will give me an error of
Sorry no opening tag
But when I try to correct it by submitting <'h1'> and <'/h1'> (disregard '), the error won't update. It still says Sorry no opening tag.
I tried using this code at the end of showMatch function
Debug.Log(outputCode);
I found that if the first input result is 2, the result everytime will always be 2. Same with if 1 is the result, the next results will be 1.
What am I doing wrong?
So I've just been making a basic little calculator made up of buttons and a textbox(tbxSum).
The problem I'm having is that if an invalid sum is input I want my catch block to pick it up(which it does) and replace what's in the textbox with the most recent result in the calculator(which it doesn't).
So say I say:
3+3=6
My calculator will now put 6 in the textbox for the next sum.
So then say I did:
6//3
It's invalid which the calculator picks up, but I want the textbox value to return to 6 from the previous sum.
This is what I've tried:
var myButton = (Button)sender;
if (myButton.Content.ToString() == "=")
{
DataTable dt = new DataTable();
string s = tbxSum.Text;
string result = "";
if (s.Contains("("))
{
s = s.Replace("(", "*(");
}
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
tbxSum.Text = v.ToString();
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
}
}
I also have a textblock(tbkSum) which shows the previous sum so I thought maybe I could take everything in there to the right of the equals sign but I have no idea how to do that.
class Calculate(){
private boolean lastGoodValueSet = false;
private int lastGoodValue = 0;
void buttonFunction(){
if (myButton.Content.ToString() == "=")
{
//Your code
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
lastGoodValue = v;
lastGoodValueSet = true;
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
if (lastGoodValueSet)
tbxSum.Text = lastGoodValue;
}
}
}
}
This is an example set of code you could use, it's a simple value that you have to store to say if a good computation has been done and if so, at the point of error we want to go back to the computation. Hope that helps! You'll want to put some kind of message to the user, so they know there was an error though.
We have to do this, as at the point of the user pressing the equals button, the value has already changed inside tbkSum, we need it before the user has changed the value, so the best time to grab it is at the point when we update the tbkSum text value at a successful calculation
This is also assuming you do not create a new instance of the Calculate class each time you do your computation. Otherwise you'd need to store the number somewhere else
EDIT
The other way to fix this issue is to instead prevent the duplicate in the first place, I read from your other comments that you control what goes into the text box by buttons on the application. Assuming all buttons go through the same method of buttonFunction() then you could do:
private char[] buttonChars = {'/','*', '+'/*e.t.c*/}
void buttonFunction(){
string buttonPressedStr = myButton.Content.ToString();
char buttonPressed = buttonPressedStr[0];
int pos = Array.IndexOf(buttonChars , buttonPressed);
if (pos > -1)
{
if (tbxSum.Text.Length > 0){
char last = tbxSum.Text[tbxSum.Text.Length - 1];
pos = Array.IndexOf(buttonChars , last);
}
else
pos = 0;
if (pos > -1){
tbkSum.Text += buttonPressedStr;
}
}
There are cleaner ways to do this, but it's an example of how you could have prevented your issue in the first place. Some explanation:
buttonChars is an array of your different button types that would be appended to your text in the box, an example is +, -, and so on
First it checks if the button pressed was in your collection of specified buttonChars
If so, we have to check what the last thing added to the tbxSum was
If the last thing added to tbxSum was again found in the buttonChars array, we don't want to append a string
Otherwise, if the tbxSum was empty or had another character at the end, we can append our character
You can store the old value in a variable declard outside the try block and use this variable in your catch block again:
string oldSumValue = tbxSum.Text;
try
{
// your code
}
catch
{
tbxSum.Text = oldSumValue ;
MessageBox.Show("Invalid Sum");
}
Alternatively I've come up with this to prevent there being:
A)Duplicate of '*' or '/'
B)Sum starting with '*' or '/'
public MainWindow()
{
InitializeComponent();
if (tbxSum.Text == "")
{
btnDiv.IsEnabled = false;
btnMult.IsEnabled = false;
}
}
protected void btnSumClick(object sender, EventArgs e)
{
btnDiv.IsEnabled = true;
btnMult.IsEnabled = true;
var myButton = (Button)sender;
int pos = tbxSum.Text.Length;
if (pos > 0)
{
if ((tbxSum.Text[pos - 1] == '/' || tbxSum.Text[pos - 1] == '*') &&
(myButton.Content.ToString() == "/" || myButton.Content.ToString() == "*"))
{
int location = tbxSum.Text.Length - 1;
tbxSum.Text = tbxSum.Text.Remove(location, 1);
}
}
}
string number = txtNumber.Text;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
break;
}
else
{
MessageBox.Show("Account Number not found");
}
}
Hello everyone, I'm fairly new here and with C# . So I have a class Account with client info which is stored in a text file.I want to loop through the array tabAccounts[200] and look if the entered user number corresponds to one that is in the text file. It works fine but when i enter let's say 222 it starts looping from the begging until it finds the number and if it doesn't it just keep looping and the message "Account Number not found" keeps coming out. When i remove the else statement it works fine but I want it that when a user enters a wrong number a message box will show...Hope you guys get it :( Tried googling but didnt find anything..
This can be done much more effective with LINQ:
var account = tabAccounts.SingleOrDefault(a => a.Number == txtNumber.Text);
if(account != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + account.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
For your original code: The problem is that you are displaying the message inside the loop, every time the loop didn't find anything. This is a rewrite close to your original syntax, just to show you how to do it:
Account foundAccount = null;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
foundAccount = ac;
break;
}
}
if(foundAccount != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + foundAccount.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
The minimum change required to achive your goal:
string number = txtNumber.Text;
bool found = false;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
found = true;
break;
}
}
if (!found)
MessageBox.Show("Account Number not found");
The problem is that you don't wait until you've finished searching to display "Account Number not found", you show it every time you find an Account that doesn't match. I'd rewrite it like this, using the FirstOrDefault extension method.
string number = txtNumber.Text;
Account ac = tabAccounts.FirstOrDefault(x => x.Number == txtNumber.Text);
if (ac != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
The best way to do this would be to set a flag when you find the element and then display outside of the loop
bool found = false;
string client;
string number = txtNumber.Text;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
found = true;
client = ac.Client;
break;
}
}
if (found)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + client;
}
else
{
MessageBox.Show("Account Number not found");
}
I have my website built in ASP.NET 2.0 and C#. I have textbox called tbCode where a user enters a code. I am trying to check that entered value against multiple values in the code behind on a button click.
This is my mark up so far.
protected void btUpdate_Click(object sender, EventArgs e)
{
if ((this.tbcode.Text.Trim().ToUpper() != "AB12") ||(this.tbcode.Text.Trim().ToUpper() != "DE14") || (this.tbcode.Text.Trim().ToUpper() != "XW16"))
{
lbmessage.Text = "Invalid Promo code. Please enter again";
}
else if ((this.tbcode.Text.Trim().ToUpper() == "AB12") || (this.tbcode.Text.Trim().ToUpper() == "DE14") || (this.tbcode.Text.Trim().ToUpper() == "XW16"))
{
Order.Shipping.Cost = 0;
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
Order.PomoCode = this.tbcode.Text.Trim().ToUpper();
lbmessage.Text = "Promo Code Applied.";
}
else
{
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
}
}
when i hit the button its always saying invalid code. not sure where am i making the mistake. It works perfectly if I am checking against just one value rather than the 3.
Thanks and appreciate it
Here is likely what you wanted to do:
protected void btUpdate_Click(object sender, EventArgs e)
{
string tbcodeValue = this.tbcode.Text.Trim().ToUpper();
string[] validCodes = new string[] { "AB12", "DE14", "XW16" };
if (!validCodes.Contains(tbcodeValue))
{
lbmessage.Text = "Invalid Promo code. Please enter again";
}
else
{
Order.Shipping.Cost = 0;
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
Order.PomoCode = tbcodeValue;
lbmessage.Text = "Promo Code Applied.";
}
}
First off, you were calling this.tbcode.Text.Trim().ToUpper() all over the place. That really clutters up your code and makes it hard to read. Assigning that to a variable not only makes the code cleaner, but avoids performing all of those string manipulation functions over and over.
Next, it appears that your intent is to say, "if the textbox value isn't any of these values, run some code saying it's invalid. The easiest way to do that is to put all of the valid values into a container of some sort and see if it contains the value you're interested in. Your next block of code is basically for, "if it is one of the valid values". So if it does contain the string then it is valid. As for your else, I couldn't figure out what the intent of it was. Either the string is invalid, or it's valid. I don't see any third case there, so I just removed it.
You need to change your ||'s to &&'s in the first if statement. You are always going to fall into that block otherwise.
Try this:
if ((this.tbcode.Text.Trim().ToUpper() != "AB12") && (this.tbcode.Text.Trim().ToUpper() != "DE14") && (this.tbcode.Text.Trim().ToUpper() != "XW16"))
{
lbmessage.Text = "Invalid Promo code. Please enter again";
}
else if ((this.tbcode.Text.Trim().ToUpper() == "AB12") || (this.tbcode.Text.Trim().ToUpper() == "DE14") || (this.tbcode.Text.Trim().ToUpper() == "XW16"))
{
Order.Shipping.Cost = 0;
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
Order.PomoCode = this.tbcode.Text.Trim().ToUpper();
lbmessage.Text = "Promo Code Applied.";
}
else
{
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
}
You could also employ a switch;case; block.
String testtext = this.tbcode.Text.Trim().ToUpper();
switch(testtext)
{
case "AB12":
// Do stuff for this case
break;
case "Text2":
// Do stuff for this case
break;
default:
// anything that fails all above tests goes here
break;
}
Just be sure to either break, return, or continue after each case or you will get a compile error. Also default needs to be last in line.