Check asp.net textbox value against multiple if conditions - c#

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.

Related

compare the items in list in c#

i want to compare the selecteditem of combobox with the selecteditem of other combobox
for this i have registered all the comboboxes in a list and named it "panel1kilist"
now the problem i am facing is that when there are same items in two comboboxes first the messagebox shows "no mattch found" and then it shows "match found" actually it goes to the else statement of inner loop first and then to if statement kindly help
private void button1_Click(object sender, EventArgs e)
{
bool check = false;
bool check1 = false;[![in this image you can see that there are two same items but message is showing "no match found"][1]][1]
try[![after clicking on ok button of message box showing "no match found" this message box shows up][1]][1]
{
for (int i = 1; i < panel1kilist.Count; i++)
{
for (int j = i + 1; j < panel1kilist.Count; j++)
{
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
}
}
}
catch (System.NullReferenceException)
{
MessageBox.Show("please fill all the boxes first");
}
}
Your question is not really clear but I still try to give you some help. As mentioned in the comments there are several small issues in your code:
1. The outter for-loop
for (int i = 1; i < panel1kilist.Count; i++)
You define i = 1, which means you skip the very first item in your panel1kilist because lists and arrays start at index 0
2. Use of your bool variables
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
You define your bool variables before starting your for-loops. So whenever you set your variables check and check1 to true, the if conditions check == false and check1 == false will never return true anymore. So you will never get any message except the very first "Match found" and "no match found".
3. My proposed solution
Make use of the foreach-loop and break the loops once you found a match, after the loops just show the message. Code:
var matchFound = false;
foreach (var combobox in panel1kilist)
{
foreach (var comboboxToMatch in panel1kilist.Skip(1))
{
if (combobox.SelectedItem.ToString() == comboboxToMatch.SelectedItem.ToString())
{
matchFound = true;
// Stops the inner loop in case of a match
break;
}
}
// Stops the outer loop in case of a match
if(matchFound)
{
break;
}
}
if(matchFound)
{
MessageBox.Show("match found");
}

Is there a way to use a variable in a catch block that was previously assigned in a try block?

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);
}
}
}

Textbox can contain letters but no numbers allowed

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.

How to jump a cycle If?

I created a Windows Form Application, which has a TextBox where you can enter a number that is modified by my program.
I created an if clause and if the TextBox.Text is empty, I do not want to run the calculations. But even if I leave the TextBox empty, an exception rises because there is no value. How can I skip this if clause?
private void button1_Click(object sender, EventArgs e)
{
string strMP3Folder = #"C:\Users\Stefano\Music\shake.mp3";
string strMP3OutputFilename = #"C:\Users\Stefano\Music\funziona2.mp3";
using (Mp3FileReader reader = new Mp3FileReader(strMP3Folder))
{
int count = 1;
Mp3Frame mp3Frame = reader.ReadNextFrame();
System.IO.FileStream _fs = new System.IO.FileStream(strMP3OutputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
double valoreIniziale = 0;
if (textBox2.Text != null)
{
valoreIniziale = Convert.ToDouble(textBox2.Text);
}
double valorefinale = 1000000;
if (textBox1.Text != null)
{ valorefinale = Convert.ToDouble(textBox1.Text); }
First thing "if" is not loop. Secondly If I understood correctly you want to neglect "if" block in case your text inside text box is empty or null. If that is what you want you can do it by :
if(!String.IsNullOrEmpty(textBox1.Text))
When you retrieve the TextBox.Text property, the "getter" runs the following code:
return (text == null) ? "" : text;
The Text property never returns null, and so your code as you currently have it will always execute.
Instead, just test for the empty string:
if (textBox2.Text != "")
{
// do something
}

Bool property is set to true without being called

I am making an web application for articles reading.
I have bool property which is set to true if the specific Edit Button is clicked, there is also a Save Button which is clicked after filling user information on TextBoxes and other controls. Whenever I run my application and fills information, it runs fine but after 4 or 5 runs (re-starting the application) it gives an Exception error upon clicking Save Button:
Input string was not in a correct format which is due to filling TextBoxes with Null( firstly, Null is converted into Int).
My problem is that bool property (Managment.IsEditing) is set to true without any reason ( Edit Button should be pressed to set bool to true). Why and how is set to true automatically as its code is only being called in EditButton_Click Event?
Here is a code
protected void EditButton_Click(object sender, EventArgs e)
{
if(EditorList.SelectedIndex > -1) //Just to ensure that Item is selected from ListBox
{
//editor is the poco , EditorManager is the editor table manager
editor = EditorManager.GetEditorInfo(EditorList.SelectedValue);
NameTextBox.Text = editor.Name;
EmailTextBox1.Text = editor.Email;
PasswordTextBox.Text = editor.Password;
EditorIDTextBox.Text = editor.Editor_ID.ToString();
for (int index = 0; index < RoleCheckBoxList.Items.Count; index++)
{
RoleCheckBoxList.Items[index].Selected = editor.RoleList[index];
}
Managment.IsEditing = true; //This flag is responsible for telling "SaveButtton" that editor would be updated.
DeleteButton.Enabled = true;
ResultLabel.Text = "";
}
else
ResultLabel.Text = "Select Editor from list first";
protected void SaveButton_Click(object sender, EventArgs e)
{
if(Managment.IsEditing == false) //it makes sure that new editor is being saved
{
editor.Name = NameTextBox.Text;
string email = EmailTextBox1.Text;
editor.Email = email.ToLower();
editor.Password = PasswordTextBox.Text;
if(EditorManager.IsEditorValid(editor.Email))
{
for (int index = 0; index < RoleCheckBoxList.Items.Count; index++)
{
editor.RoleList[index] = RoleCheckBoxList.Items[index].Selected;
}
EditorManager.Save(editor);
ResultLabel.Text = editor.DataUploadMessage;
}
else
ResultLabel.Text = "Editor with the same Email can't be add!";
FillEditorList();
}
else if(Managment.IsEditing == true) //it determines that existing editor is being updated and problem is that Managment.IsEditing is turned on without being called.
{
editor.Name = NameTextBox.Text;
string email = EmailTextBox1.Text;
editor.Email = email.ToLower();
editor.Password = PasswordTextBox.Text;
editor.Editor_ID = Convert.ToInt32(EditorIDTextBox.Text);// Error occurs at this line
for (int index = 0; index < RoleCheckBoxList.Items.Count; index++)
{
editor.RoleList[index] = RoleCheckBoxList.Items[index].Selected;
}
EditorManager.Edit(editor);
ResultLabel.Text = editor.DataUploadMessage;
Managment.IsEditing = false;
FillEditorList();
}
ClearFields(Form.Controls);
}
Exception occurs on that line:
editor.Editor_ID = Convert.ToInt32(EditorIDTextBox.Text);
and sorry for any inconvenience dear fellows
When the exception occurs on the indicated line, the line that resets your flag won't be run. The page will then likely be in an invalid state.
Try fixing/handling the error and clean up properly, and the problem might go away.

Categories