How to use backspace which stops at the number 0 - c#

I am new to c# and I am trying to create a backspace button (for a calculator) that when pressed, can only backspace until the textbox has reached 0.
i don't know what else to add, so far I am at:
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
so far its able to backspace to " " then eventually crashes if used again.
i wish to limit the backspace button so if there's no more text entered in the field, it will automatically change the text to "0".
Answered, thanks guys :)

Use String.IsNullOrEmpty
private void backSpaceButton_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(displaytxt.Text))
{
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
}
}

You have to apply check before calling substring
if(string.Empty != displaytxt.Text)
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
or you can check the length
if(displaytxt.Text.Length > 0)
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);

You say you want to never get an empty string, you want to get "0" if you backspace while you only have a single character left. So, check if you have a single-character string:
if (displaytxt.Text.Length == 1)
displaytxt.Text = "0";
else
displaytxt.Text = displaytxt.Text.Substring(0, displaytxt.Text.Length - 1);
Note: make sure you don't have any other code that sets displaytxt.Text to an empty string.

You can try this way :
displaytxt.Text = displaytxt.Text.Length > 1 ?
displaytxt.Text.Substring(0, displaytxt.Text.Length - 1) :
"0";

If you wnat to emulate BackSpace key you can do something like that:
private void backSpace_Click(object sender, EventArgs e) {
if (displaytxt.SelectionLength > 0)
displaytxt.Text = displaytxt.Text.Remove(displaytxt.SelectionStart, displaytxt.SelectionLength);
else if (displaytxt.SelectionStart > 0) {
int start = displaytxt.SelectionStart;
displaytxt.Text = displaytxt.Text.Remove(start - 1, 1);
displaytxt.Select(start - 1, 0);
}
}
If you want just to remove the last char you can achive it
private void backSpace_Click(object sender, EventArgs e) {
if (!String.IsNullOrEmpty(displaytxt.Text))
displaytxt.Text = displaytxt.Text.Remove(displaytxt.Text.Length - 1);
}

Related

Why does my backspace return a new text instead of updating the current text?

I am trying my hand at a self teaching project by creating a calculator. I am having trouble getting my backspace to update the text in my textbox. My goal is to be able to Backspace using my backspace button and add a number afterward and having my result being exactly whats expected with any backspace i.e.
(1) string of 701
(2) Backspace used
(3) Adding 4 to the string
(4) return 704
What I am thinking is that when I click the button it is returning a new string and when I enter a new number, it is updating the old string. I have tried this code in the btnBck_Click function as well as what I am showing in my current code(the BackSpaceFunction(); is my attempt to tell the program to return the updated string).
private void btnBck_Click(object sender, EventArgs e)
{
BackSpaceFunction();
}
private string BackSpaceFunction()
{
string textBoxText = textBox1.Text;
textBoxText = textBox1.Text.Remove(textBoxText.Length - 1);
if (textBox1.Text.Length >= 1)
{
textBox1.Text = textBox1.Text.Replace(textBox1.Text, textBoxText);
return textBox1.Text;
}
else if (textBox1.Text.Length == 0)
{
textBox1.Text = "0";
input = string.Empty;
operand1 = string.Empty;
operand2 = string.Empty;
}
return textBox1.Text;
}
(Please understand my excessive explaining and use of examples is to make sure everyone can understand in case I myself missed the point. Thank you in advance)
I am having trouble getting my backspace to update the text in my textbox
The TextBox control supports use of the backspace key directly. As long as the TextBox has the input focus, pressing the backspace key will delete the character just before the current insertion point.
Your code example is incomplete, but it looks like you have a separate Button object that is intended to provide similar functionality. You aren't taking into account the insertion point for the TextBox, so presumably you just always want to remove the last character. If that's the case, your method is far more complicated than it needs to be. You can just use string.Substring() to remove the last character:
private string BackSpaceFunction()
{
if (textBox1.Length > 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "0";
input = string.Empty;
operand1 = string.Empty;
operand2 = string.Empty;
}
return textBox1.Text;
}
(You never actually use the return value, so it's not clear why the method has a return value. But I left that in because it's not inherently a problem.)
So to answer my own question, I took the time to try and figure it out for myself. I ended up succeeding and found that this code worked (look at the "if" portion of my if statement).
private void btnBck_Click(object sender, EventArgs e)
{
BackSpaceFunction();
}
private string BackSpaceFunction()
{
//textBoxText = textBox1.Text.Remove(textBoxText.Length - 1);
if (textBox1.Text.Length >= 1)
{
string textBoxText = textBox1.Text.Remove(textBox1.Text.Length - 1);
string updatedText = textBox1.Text = textBox1.Text.Replace(textBox1.Text, textBoxText);
textBox1.Text = updatedText;
input = string.Format(textBox1.Text, updatedText);
operand1 = string.Format(textBox1.Text, updatedText);
operand1 = string.Format(textBox1.Text, updatedText);
}
else if (textBox1.Text.Length == 0)
{
textBox1.Text = "0";
input = string.Empty;
operand1 = string.Empty;
operand2 = string.Empty;
}
return textBox1.Text;
}'''
I'm not exactly sure why I had to use Format for input, operand1, and operand2 but it ended up doing exactly what I needed. If there are any explanations as to why this worked I will gladly accept the learning opportunity. :)

How to insert hyphen "-" after 2 digits automatically in TextBox?

I have one TextBox for user to input number.
When user input to the TextBox then the format should be like this
01-22-34-40-33
I want to insert "-" after 2 digits in the TextChanged event handler.
I do something like this but no work:
if(txtRandomThirdTypeSales.Text.Length == 2)
{
txtRandomThirdTypeSales.Text += "-";
}
else if (txtRandomThirdTypeSales.Text.Length == 5)
{
txtRandomThirdTypeSales.Text += "-";
}
else if (txtRandomThirdTypeSales.Text.Length == 8)
{
txtRandomThirdTypeSales.Text += "-";
}
else if (txtRandomThirdTypeSales.Text.Length == 11)
{
txtRandomThirdTypeSales.Text += "-";
}
Can you please try this way,this may be will helpful for you.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string sVal = textBox1.Text;
if (!string.IsNullOrEmpty(sVal) && e.KeyCode != Keys.Back)
{
sVal = sVal.Replace("-", "");
string newst = Regex.Replace(sVal, ".{2}", "$0-");
textBox1.Text = newst;
textBox1.SelectionStart = textBox1.Text.Length;
}
}
Let me know if you need any help.
Maybe you can try this
if(txtRandomThirdTypeSales.Text.Count(x => x != '-') % 2 == 0)
{
txtRandomThirdTypeSales.Text += "-";
}
That way it counts all the chars that are not a - and checks if they are even. If they are, add the '-'.
You can make it more restrictive by checking that they are digits with a regex. ^\d
Can you please try this
if(txtRandomThirdTypeSales.Text.Length % 3 == 2)
{
txtRandomThirdTypeSales.Text += "-";
}
You can also add code to handle backspace key down and delete key down.
Have you tried TextBox masking? it is available in Winform controls
Here is your reference http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx

How to prevent the first character to be a number

I have a textbox control and allowing the user to enter only letters or numbers:
private void tbTableName_TextChanged(object sender, EventArgs e)
{
tbTableName.Text = string.Concat(tbTableName.Text.Where(char.IsLetterOrDigit));
if (tbTableName.Text.Length > 0)
{
btnConvert.Enabled = true;
}
else
{
btnConvert.Enabled = false;
}
}
How can I modify so that the first character cannot be a digit, only letter and then they can add as many digit as they want?
I have a WinForm, not a Web Form.
You just need to modify this line:
if (tbTableName.Text.Length > 0)
to:
if (tbTableName.Text.Length > 0 && !Char.IsDigit(tbTableName.Text[0]))
Why not using regular expression?
I edit the regular expression to allow user to add digit or letter after the first digit
btnConvert.Enabled = System.Text.RegularExpressions.Regex.IsMatch(input, "^[a-zA-Z][a-zA-Z0-9 ]+$");
private void tbTableName_TextChanged(object sender, EventArgs e)
{
string name = Regex.Replace(tbTableName.Text, #"^\d+|\W", string.Empty);
btnConvert.Enabled = name.Length > 0;
tbTableName.Text = name;
}
You could just remove the first character if it's a number:
if (tbTableName.Text.Length > 0 && char.IsNumber(tbTableName.Text[0]))
tbTableName.Text = tbTableName.Text.Substring(1);

Getting integer from textbox

I want to write the event handler method button1_Click to calculate whether student’s Grade is “PASS” or “FAIL”. The student passes the course if the total score is greater than or equal to 50. The total score is Midterm(textbox1) + Final(textbox2) scores. However, teacher can give student Extra Credit(checkbox1) which is worth 10 points. The result will present in the textBox3
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
int midtermInt = int.Parse(textBox1.Text);
int finalInt = int.Parse(textBox2.Text);
if (checkBox1.Checked)
{
if ((midtermInt + finalInt) + 10 >= 50)
{
grade.Text = "PASS";
}
else if ((midtermInt + finalInt) + 10 < 50)
{
grade.Text = "FAIL";
}
}
else if (!checkBox1.Checked)
{
if ((midtermInt + finalInt) >= 50)
{
grade.Text = "PASS";
}
else if ((midtermInt + finalInt) < 50)
{
grade.Text = "FAIL";
}
}
When I run it, it says "Inut string was not in a correct format.. :(
I'm very new to C# please advise me if my code is wrong anywhere
The input will only be integers never texts..
You should use int.TryParse insted int.Parse, it's check is specified string is in correct format.
You code may looks like this:
int midtermInt;
if (!int.TryParse(textBox1.Text, out midtermInt))
{
labelError.Text = "Icorrect value in field 'textBox1'".
return;
}
If you type non-numeric characters in your textbox and try to parse the text, it will throw you this exception. Try trimming the input and definitely consider adding UI validation to your forms.
You can add checking, if text in text box is in correct format in TextChanged event:
private void textBox_TextChanged(object sender, EventArgs e)
{
int val;
if (textBox.Text.Length == 0 || !int.TryParse(textBox.Text, out val))
tsPassingScore.Text = "0";
}
And in your click you can check if there is number in textBox again with int.TryParse
Also you can improve your code:
If final summ is not bigger then 50 - it is automatically smaller! And it would be more readable, if you introduce extra variable - for teachers extra credit:
int extraCredit = checkBox1.Checked ? 10 : 0;
int finalScore = midtermInt + finalInt + extraCredit;
if (finalScore >= 50)
grade.Text = "PASS";
else
grade.Text = "FAIL";

how to type to a label?

I am trying to have a multi line textbox that when you type in it streams it to the label, BUT the label has to have a max length of 15 so like once it reaches 15 characters in the textbox it should start overwriting the label since it reached it's max length
thanks to anyone who can help
Add onchange event on text box :
if (textBox1.Text.Length<=15)
{
label1.Caption=textBox1.Text;
}
For example
I'm not sure what kind of overwriting You want to achieve.
There are at least three methods you can use:
displaying always the last 15 characters from the textbox, as described in the Olivier's answer
clearing the label's text each 15 characters inserted and start filling in the label over again, you can use this code to achieve this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
String text = textBox1.Text.Replace("\r\n", "|");
int startIndex = ((text.Length - 1) / 15) * 15;
label1.Text = text.Substring(Math.Max(0, startIndex));
}
you can also overwrite char by char when text length is over 15 characters, however, I suppose it's not what you would like to achieve, because it would cause a mess in the textbox ;), however, it can be used as a kind of visual effect :). If you want code snippet for this, let me know :).
Update
Here's the code for the third overwriting method:
String lastText = "";
private void textBox1_TextChanged(object sender, EventArgs e)
{
String textBoxText = textBox1.Text.Replace("\r\n", "|");
if (textBoxText.Length > lastText.Length)
{
int charIndex = (textBoxText.Length - 1) % 15;
if (charIndex >= 0)
{
label1.Text = label1.Text.Insert(charIndex, textBoxText.Substring(textBoxText.Length - 1));
if (charIndex < textBoxText.Length - 1)
{
label1.Text = label1.Text.Remove(charIndex + 1, 1);
}
}
}
else
{
int charIndex = textBoxText.Length % 15;
if (textBoxText.Length >= 15)
{
label1.Text = label1.Text.Insert(charIndex, textBoxText[textBoxText.Length - 15].ToString());
if (charIndex < textBoxText.Length - 1)
{
label1.Text = label1.Text.Remove(charIndex + 1, 1);
}
}
else
{
label1.Text = label1.Text.Remove(label1.Text.Length - 1, 1);
}
}
lastText = textBoxText;
}
Add a handler to the TextChanged event of the TextBox that sets the Label's content based on the text. E.g. (untested, might have your concept wrong or be off by one somewhere)
int startIndex = Math.Max(0, myTextBox.Text.Length - 15);
int endIndex = Math.Min(myTextBox.Text.Length - 1, startIndex);
myLabel.Text = myTextBox.Text.Substring(startIndex, endIndex - startIndex);
Also, though it doesn't change your question/answer, you might want to look at using a TextBlock instead of a Label. It allows things like line wrapping. See some of the differences here: http://joshsmithonwpf.wordpress.com/2007/07/04/differences-between-label-and-textblock/ (in WPF, should be similar whatever you're doing, though)
My solution always displays the last 15 characters in the label
private void textBox1_TextChanged(object sender, EventArgs e)
{
string s = textBox1.Text.Replace("\r\n", "|");
int length = s.Length;
if (length > 15) {
label1.Text = s.Substring(length - 15);
} else {
label1.Text = s;
}
}
I also replace the line-breaks with |. Since your textbox is in multiline mode, line-breaks are entered when you hit <Enter>.

Categories