How to jump a cycle If? - c#

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
}

Related

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

How to validate if the values of four text box is empty string or not and assign these text box as "0" value if it is empty in C# with minimal code

I have four text box in C# ,If the value of any text box is :empty string,then it must be assigned as '0'.I have tried the following code which seems to be lenghty .
if (txtReset1.Text == "")
{
txtReset1.Text = "0";
}
if (txtReset2.Text == "")
{
txtReset2.Text = "0";
}
if (txtReset3.Text == "")
{
txtReset3.Text = "0";
}
if (txtReset4.Text == "")
{
txtReset4.Text = "0";
}
Is there any more efficient code than the above one?
Rather than repeat yourself, create a new method to handle it:
private void SetEmptyTextBoxToZero(TextBox textBox)
{
if (textBox != null && string.IsNullOrEmpty(textBox.Text)
{
textBox.Text = "0";
}
}
Then you replace your code with:
SetEmptyTextBoxToZero(txtReset1);
SetEmptyTextBoxToZero(txtReset2);
SetEmptyTextBoxToZero(txtReset3);
SetEmptyTextBoxToZero(txtReset4);
As " Binkan Salaryman" suggests, if you have lots of text boxes that need to be handled this way, then you can store references to them in a list and then iterate over them, rather than listing them out as above:
var textBoxes = new List<TextBox> { txtReset1, txtReset2, txtReset3, txtReset4 };
...
// Option 1: using .ForEach()
textBoxes.ForEach(tb => SetEmptyTextBoxToZero(tb));
// Option 2: using foreach
foreach (var tb in textBoxes)
{
SetEmptyTextBoxToZero(tb);
}

Verify a Color Has Been Inputted in a DataGridView

I have a datagridview where one of the columns is a color column. I want to ensure the user enters a valid color, otherwise leave the cell blank.
When the cell is starting from blank, the following code gives me a null reference exception. Fyi, I am doing this in the CellLeave event.
Answer I had to move the code to the CellFormatting event. For some reason, the value at the cell does not get updated until a certain unknown point. For my check, I need to do it before something I was doing in the CellFormatting event. Moving the code there fixed my problem.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex.Equals(2))
{
Regex test = new Regex("[0-255],[0-255],[0-255]");
Match m = test.Match(this.dataGridView1.CurrentCell.Value.ToString());
if(!m.Success)
{
this.dataGridView1.CurrentCell.Value = "";
}
}
}
To validate a string you could use this method:
private static bool IsValidColorString(string input)
{
if (String.IsNullOrEmpty(input))
return false;
string[] parts = input.Split(',');
if (parts.Length != 3)
return false;
foreach (string part in parts)
{
int val;
if (!int.TryParse(part, out val) || val < 0 || val > 255)
return false;
}
return true;
}
The best place to use it I believe is the DataGridView.CellParsing event handler:
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
if (e.Value == null || e.ColumnIndex != 2) // Skip empty cells and columns except #2
return;
string input = e.Value.ToString();
if (!IsValidColorString(input))
e.Value = String.Empty; // An updated cells's value is set back to the `e.Value`
}
An updated cells's value is set back to the e.Value instead of the DataGridView.CurrentCell.Value.
Try this for your match:
Match m = test.Match((this.dataGridView1.CurrentCell.Value ?? "").ToString());
This will replace a null value with an empty string when matching.
Do you perhaps need to check to see if there is a value within the cell before you try and match a Regex?
if (e.ColumnIndex.Equals(2))
{
if(this.dataGridView1.CurrentCell.Value != null)
{
...
CurrentCell.Value.ToString()
Causing the error..
CurrentCell.value=null
null value can't cast using the tostring() method,that's why you are getting ther null reference exception.
try this..
string val="";
if(dataGridView1.CurrentCell.Value==null)
{
val=""
}
els
else
{
val=convert.tostring(dataGridView1.CurrentCell.value);
}
Match m = test.Match(val);
if(!m.Success)
{
this.dataGridView1.CurrentCell.Value = "";
}

Textbox KeyPress Event?

i have textbox only allow decimals and '+'
it allow only 1 Decimal "12.332" i need to allow 1 decimal before '+' and 1 decimal after '+' Example i have 12.43+12.23 i can't type the 12(.) because i allow only 1 decimal i am using Split method to get 2 parts before and after
and it is my code
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
And this is My method
if(textBox1.Text.Contains('+')==true )
{
string Value = textBox1.Text;
string[] tmp = Value.Split('+');
string FirstValu = tmp[1];
string SecValu = tmp[0];
}
how to use method with event to allow another decimal place after '+'
I would say use two text boxes like someone said in the comments but if you want to be stubborn here is a function to run inside an event that is called when the text changes in the text box.
void textbox_textChanged(object sender, EventArgs e)
{
string text = textBox.Text;
int pointCounter = 0;
int addCounter =0
string temp = "";
string numbers = "0123456789";
for(int i =0;i<text.Length;i++)
{
bool found = false;
for(int j = 0;j<numbers.Length;j++)
{
if(text[i]==numbers[j])
{
temp+=text[i];
found = true;
break;
}
}
if(!found)
{
if('.' == text[i])
{
if(pointCounter<1)
{
pointCounter++;
temp+=text[i];
}
}else
if('+' == text[i])
{
if(addCounter<1)
{
pointCounter=0;
addCounter++;
temp+=text[i];
}
}
}
}
textBox.text = temp;
}
I would recommend using a Regex to validate your textbox. I would also suggest that using the textbox Validating event would be better than using the Leave event. Here is an example of using a regex in the Validating event:
private void textBox1_Validating(object sender, CancelEventArgs e)
{
TextBox tbox = (TextBox)sender;
string testPattern = #"^[+-]?[0-9]*\.?[0-9]+ *[+-]? *[0-9]*\.?[0-9]+$";
Regex regex = new Regex(testPattern);
bool isTextOk = regex.Match(tbox.Text).Success;
if (!isTextOk)
{
MessageBox.Show("Error, please check your input.");
e.Cancel = true;
}
}
You will find the Regex class in the System.Text.RegularExpressions namespace. Also make sure your textbox has the CausesValidation property set to true.
As an alternative you might also want to look at using the MaskedTextBox Class.

Check asp.net textbox value against multiple if conditions

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.

Categories