c# button click increase alphabet letter - c#

I have a button on a c# form that when it is clicked, should change its text value to the next letter in the alphabet sequence.
The default button value is a dash "-" (when the application starts). When the button is clicked, it should change to A, and when it's click again, change to B. At Z, it should reset to A.
I have the following code, however, when the button is pressed, it just returns an open bracket "[".
private void alphaCode_Click(object sender, EventArgs e)
{
string s = null;
for (char c2 = 'A'; c2 <= 'Z' + 1; c2++)
{
s = c2.ToString();
}
alphaCode.Text = s;
}

You do not need a loop in the alphaCode_Click, because the cycle happens outside of the "on click" event handler. It's the user who does the looping (by clicking a button); your code performs a single step of that loop.
Therefore, all you need is to pick the letter from the alphaCode.Text, add one to it, and set it back into the alphaCode.Text field:
private void alphaCode_Click(object sender, EventArgs e)
{
string s = null;
var current = alphaCode.Text.Length == 1 ? alphaCode.Text[0] : 'A';
if (current >= 'A' && current <= 'Z') {
current++;
} else {
current = 'A';
}
alphaCode.Text = "" + current;
}

A solution that does not depend on the current text value and works for any alphabet:
string const Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int _currentCharacterIndex = -1;
private void alphaCode_Click(object sender, EventArgs e)
{
_currentCharacterIndex = (_currentCharacterIndex +1) % Alphabet.Count;
alphaCode.Text = Alphabet[_currentCharacterIndex ];
}
(Untested. I don't have access to Visual Studio right now.)

You are enumerating through all the letters as soon as the button is pressed. Basically, you only want to advance your character once per press.
private void alphaCode_Click(object sender, EventArgs e)
{
char currentChar = alphaCode.Text[0];
if(currentChar == '-')
{
alphaCode.Text = "A";
}
else
{
char newChar = currentChar + 1;
if(newChar > 'Z')
{
newChar = 'A';
}
alphaCode.Text = newChar;
}
}

Use the ASCII code of current text as tag for the button. On each click, increase it and change the text. Now, once you have moved through the range (Z that is), reset to a.
Are you dealing with both uppercase and lowercase?

private void alphaCode_Click(object sender, EventArgs e)
{
char s = Convert.ToChar(alphaCode.Text.Trim());
if (s == '-' || s == 'Z')
{
alphaCode.Text = "A";
}
else
{
s++;
alphaCode.Text = s.ToString();
}
}

The char Z is the 90th (dec) in the ASCII table, so when you loop until 90 + 1 = 91, and assign the textBox to it, it shows '[' which is the 91th. For the sake of simplicity, have a char created as a field (within the class, not any function or procedure), and everytime the user clicks you just assign the textbox to the current value and then increment it.
private void alphaCode_Click(object sender, EventArgs e)
{
txtAlph.Text = currentChar.ToString();
currentChar++;
}
Then, as a field, just use a char to hold the value:
char currentChar = 'A';

Set your char as an field. And increase the value of c with every buttonclick. If c = Z then start again on A...
char c = 'A';
private void button_Click(object sender, EventArgs e) {
if(c == 'Z'){
c = 'A';
}
label1.Text = c + "";
c++;
}

Just loop through the char code
public partial class Form1 : Form
{
private int _charCode = 65;
public Form1()
{
InitializeComponent();
alphaCode.Text = "-";
}
private void alphaCode_Click(object sender, EventArgs e)
{
// 90 is 'Z'
if (_charCode > 90)
_charCode = 65;
alphaCode.Text = ((char)_charCode).ToString();
_charCode++;
}
}

Related

Removing spaces in MaskedTextBox on Leave Event - IP Address Validation

I'm trying to do IPv4 validation in a maskedtextbox. My mask is set to ###.###.###.### and i have my Key Down Event handling the '.' key as going to next octet which works great... However, if an IP address dows not have 3 digits in each octet i get random spaces when I grab the textfield for use.
For example: if I type 72.13.12.1 the output is "72 .13 .12 .1" <- I don't want the spaces.
I've tried doing some validation like removing the spaces once I leave the maskedtextbox, but if I remove the spaces, my mask kicks back in and changes it to "721.321.1 ."
this.maskedTextBoxExternIP.ResetOnSpace = false;
this.maskedTextBoxExternIP.SkipLiterals = false;
this.maskedTextBoxExternIP.PromptChar = ' ';
this.maskedTextBoxExternIP.Mask = "###.###.###.###";
this.maskedTextBoxExternIP.ValidatingType = typeof(System.Net.IPAddress);
this.maskedTextBoxExternIP.KeyDown += new KeyEventHandler(this.maskedTextBoxExternIP_KeyDown);
this.maskedTextBoxExternIP.Enter += new EventHandler(this.maskedTextBoxExternIP_Enter);
this.maskedTextBoxExternIP.Leave += new EventHandler(this.maskedTextBoxExternIP_Leave);
private void maskedTextBoxExternIP_Leave(object sender, EventArgs e)
{
// Resets the cursor when we leave the textbox
maskedTextBoxExternIP.SelectionStart = 0;
// Enable the TabStop property so we can cycle through the form controls again
foreach (Control c in this.Controls)
c.TabStop = true;
IPAddress ipAddress;
if (IPAddress.TryParse(maskedTextBoxExternIP.Text, out ipAddress))
{
//valid ip
}
else
{
//is not valid ip
maskedTextBoxExternIP.Text = maskedTextBoxExternIP.Text.Replace(" ", string.Empty);
}
}
// Handle the Enter event
private void maskedTextBoxExternIP_Enter(object sender, EventArgs e)
{
// Resets the cursor when we enter the textbox
maskedTextBoxExternIP.SelectionStart = 0;
// Disable the TabStop property to prevent the form and its controls to catch the Tab key
foreach (Control c in this.Controls)
c.TabStop = false;
}
// Handle the KeyDown event
private void maskedTextBoxExternIP_KeyDown(object sender, KeyEventArgs e)
{
// Cycle through the mask fields
if (e.KeyCode == Keys.Tab || e.KeyCode == Keys.OemPeriod || e.KeyCode == Keys.Decimal)
{
int pos = maskedTextBoxExternIP.SelectionStart;
int max = (maskedTextBoxExternIP.MaskedTextProvider.Length - maskedTextBoxExternIP.MaskedTextProvider.EditPositionCount);
int nextField = 0;
for (int i = 0; i < maskedTextBoxExternIP.MaskedTextProvider.Length; i++)
{
if (!maskedTextBoxExternIP.MaskedTextProvider.IsEditPosition(i) && (pos + max) >= i)
nextField = i;
}
nextField += 1;
// We're done, enable the TabStop property again
if (pos == nextField)
maskedTextBoxExternIP_Leave(this, e);
maskedTextBoxExternIP.SelectionStart = nextField;
}
}
#madreflection I finally got the IPAddressCrontrolLib to work I just used the source files and embedded the library that way. Had to do a little fudging around to clear all the errors that we there. All good now! Just needed a new day to get through that one. Thanks for your help.

When I put two or more operators in eg '*' and error occurs, feel free to edit code

Operation error when two operations are clicked, i want error handling to take place so i cant put multiple * in a row
namespace Calculator_Assignment
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
float num, ans;
int count;
private void Form1_Load(object sender, EventArgs e)
{
}
private void Button_click(object sender, EventArgs e)
{
Button button = (Button)sender; //adds the numbers into the screen when clicked
Screen.Text = Screen.Text + button.Text;
Screen.ForeColor = Color.Red; //text that entered appears red
}
private void operatorclick(object sender, EventArgs e)
{
Button button = (Button)sender; //adds the symbols into the screen when clicked
Screen.Text = Screen.Text + button.Text; //all symbols are under button_click so i do not have to repeat the code over/
}
private void Clearclick(object sender, EventArgs e)
{
Screen.Clear(); //when clicked clears the screen
Result.Clear(); //when clicked clears the result
}
private void Decimalclick(object sender, EventArgs e)
{
Screen.Text = Screen.Text + "."; //adds decimal point to screen when/if clicked
Screen.ForeColor = Color.Red; //decimal point appears red
}
private void Closebtn_Click(object sender, EventArgs e)
{
this.Close(); // closes the application down
}
private void plusclick(object sender, EventArgs e) //addition
{
num = float.Parse(Screen.Text);
Screen.Clear(); //clears the screen of everything
Screen.Focus(); //textbox is focused upon when the screen is cleared
count = 1; //this counts the store case
Screen.Text = num.ToString() + "+"; //this puts the text onto the top text box
}
private void multiplyclick(object sender, EventArgs e) //multiply
{
num = float.Parse(Screen.Text);
Screen.Clear(); //clears the screen of everything
Screen.Focus(); //textbox is focused upon when the screen is cleared
count = 3; //this counts the store case
Result.Text = num.ToString() + "*"; //this puts the text onto the top textbox
}
private void divideclick(object sender, EventArgs e) //divide
{
num = float.Parse(Screen.Text);
Screen.Clear(); //clears the screen of everything
Screen.Focus(); //textbox is focused upon when the screen is cleared
count = 4; //this counts the store case
Screen.Text = num.ToString() + "/"; //this puts the text onto the
}
private void subtractclick(object sender, EventArgs e) //subtract
{
num = float.Parse(Screen.Text);
Screen.Clear(); //clears the screen of everything
Screen.Focus(); //textbox is focused upon when the screen is cleared
count = 2; //this counts the store case
Result.Text = num.ToString() + "-"; //this puts the text onto the label
}
private void equalsclick(object sender, EventArgs e)
{
switch (count) //initalising switch statement
{
case 1:
ans = num + float.Parse(Screen.Text);//Adding numbers
Result.Text = ans.ToString(); //this converts my answer from a float to a string
break;
case 2:
ans = num - float.Parse(Screen.Text); //Subtracting numbers
Result.Text = ans.ToString(); //float to a string
break;
case 3:
ans = num * float.Parse(Screen.Text); //Multiplying numbers
Result.Text = ans.ToString(); //float to a string
break;
case 4:
ans = num / float.Parse(Screen.Text); //Division of numbers
Result.Text = ans.ToString(); //float to a string
break;
default: //the default figure
break;
}
}
}
}
Quick solution:
Create a method called void AppendOperator(string operator)
This method should check the previous character before appending it. If the previous character is an operator then simply return.
Call this new method in place of all the locations where you assign a value to Result.Text
AppendOperator implementation example:
private readonly HashSet<char> _operators = new HashSet<char>() { '+', '*', '-', '/' };
void AppendOperator(string operation)
{
char lastChar = Result.Text.LastOrDefault();
if (_operators.Contains(lastChar)) return;
Result.Text = num.ToString() + operation;
}

AutoComplete characters as ( and }

I am developing a simple text editor, and I'm having trouble doing the self add some character ... I did the following sample code, what I'm doing ... When I type the character, it does not add its corresponding char in current cursor position....
Another doubt, how can I make the program ignore the characters added when I type it again ...??
Dictionary<char, char> glbin = new Dictionary<char, char>
{
{'(', ')'},
{'{', '}'},
{'[', ']'},
{'<', '>'}
};
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int line = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);
int column = textBox1.SelectionStart - textBox1.GetFirstCharIndexFromLine(line);
if(glbin.ContainsKey(e.KeyChar))
textBox1.Text.Insert(column, glbin[e.KeyChar].ToString());
}
String is immutable object, and Insert call on Text property produces new instance of string, which is not assigned anywhere.
And to ignore char you need to set KeyPressEventArgs Handled property to true (you would probably need inverse dictionary of closing chars).
You need to change your code to:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int index = textBox1.SelectionStart;
if(glbin.ContainsKey(e.KeyChar))
{
var txt = textBox1.Text; // insert both chars at once
textBox1.Text = txt.Insert(index, e.KeyChar + glbin[e.KeyChar].ToString());
textBox1.Select(index + 1, 0);// position cursor inside brackets
e.Handled = true;
}
else if (glbin.Values.Contains(e.KeyChar))
{
// move cursor forward ignoring typed char
textBox1.SelectionStart = textBox1.SelectionStart + 1;
e.Handled = true;
}
}

Remove String from Text Box from back

I have a requirement in C# where I have a text box with numbers delimited by ; say e.g.
(205)33344455;918845566778;
Now when a user presses ← Backspace (to remove the number) one character at a time gets deleted. I want to delete the whole number at once.
So when the user presses ← the first time, the number will be highlighted
i.e. if text is (205)33344455;918845566778;, the 918845566778; part will be highlighted in say black, and when the user presses ← again the whole number i.e. 918845566778; will be deleted.
So is it possible to highlight a particular section in text box, and delete the whole number?
I used a for loop like:
for{back=txtPhone.Text.Length;back<=txtPhone.Text.indexOf(';');back--)
But I was not able to achieve the desired result.
Any help on this would be great.
You can implement your requirement as shown below
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.Text.Length == 0) return;
if ((e.KeyChar == (char)Keys.Back) && (textBox1.SelectionLength == 0))
{
textBox1.SelectionStart = Math.Max(0, textBox1.Text.Substring(0,textBox1.Text.Length-1).LastIndexOf(';'));
if (textBox1.Text.Substring(textBox1.SelectionStart, 1) == ";") textBox1.SelectionStart++;
textBox1.SelectionLength = textBox1.Text.Length-textBox1.SelectionStart ;
e.Handled = true;
return;
}
if ((e.KeyChar == (char)Keys.Back) && textBox1.SelectionLength >= 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.SelectionStart );
textBox1.SelectionStart = textBox1.Text.Length;
e.Handled = true;
}
}
A couple of methods to achieve want you want come to mind:
Subscribing the text box to Control.Keydown event which would check for the ← button and perform the highlight up to the last delimiter (;) using TextBox.SelectionLength meaning a ← Backspace will clear it.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Left)
return;
e.SuppressKeyPress = true;
//Select up to previous delimeter (;) here
}
Use a listbox (or something similar) to store the delimited data as it is entered. This will allow the user to select what they need, and remove it via a button you will provide.
You can :
Select the token (i.e. number terminated by ;) that contains the cursor (method selectToken())
Remove it when backspace is
pressed a second time
Example:
your textbox contains '(205)33344455; 918845566778; 8885554443;'
you click with the left mouse button between 9188455 and 66778; (second number)
then you press backspace
the string 918845566778; gets selected
you press backspace a second time and that string gets deleted
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Remove_String_from_Text_Box_from_back
{
public partial class Form1 : Form
{
//selects token that contains caret/cursor
private void selectToken() {
string str0 = textBox1.Text;
int caretPosition = textBox1.SelectionStart;
int tokenEndsAtIndex = str0.IndexOf(';', caretPosition, (textBox1.Text.Length - caretPosition));
string prefix = "";
if (tokenEndsAtIndex == -1)
{
tokenEndsAtIndex = str0.IndexOf(';');
}
prefix = str0.Substring(0, tokenEndsAtIndex);
int tokenStartsAtIndex = 0;
tokenStartsAtIndex = prefix.LastIndexOf(';');
if (!(tokenStartsAtIndex > -1)) { tokenStartsAtIndex = 0; } else { tokenStartsAtIndex++; }
textBox1.SelectionStart = tokenStartsAtIndex;
textBox1.SelectionLength = tokenEndsAtIndex - tokenStartsAtIndex + 1;//may be off by one
}
private void selectLastToken(string str0)
{
Regex regex = new Regex(#"([\d()]*;)$");
var capturedGroups = regex.Match(str0);
int idx0 = 0;
if (capturedGroups.Captures.Count > 0)
{
idx0 = str0.IndexOf(capturedGroups.Captures[0].Value, 0);
textBox1.Select(idx0, textBox1.Text.Length);
}
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "(205)33344455;918845566778;";
textBox1.Select(0, 0);
}
//selects last token terminated by ;
private void selectTextOnBackSpace()
{
string str0 = textBox1.Text;
int idx0 = str0.LastIndexOf(';');
if (idx0<0)
{
idx0 = 0;
}
string str1 = str0.Remove(idx0);
int idx1 = str1.LastIndexOf(';');
if (idx1 < 0)
{
idx1 = 0;
}
else
{
idx1 += 1;
}
textBox1.SelectionStart = idx1;
textBox1.SelectionLength = str0.Length - idx1;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back )
{
if (textBox1.SelectionLength==0)
{
selectToken();
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}
}
}

Select a particular line in textbox?

I have a two forms, 1 and 2. Form1 has one textbox and form2 has a textbox and button. I want to go to a specified line, meaning that when I enter the value of form2's textbox then my mouse cursor goes to form1's textbox.
private void button1_Click(object sender, EventArgs e)
{
int line = Form1.ab;
for (int i = 1; i < line; i++)
{
if (i == Convert.ToInt16( textBox1.Text))
{
// fr.textbox1 is a textbox form1 and
// textbox1.text is a textbox of the form1
fr.textBox1.SelectionStart =
int.Parse( textBox1.Text) ;
fr.textBox1.ScrollToCaret();
break;
}
}
}
The TextBox.GetFirstCharIndexFromLine method finds the index of the first character of a line.
So your selection starts there. Then find the end of that line, which is Environment.NewLine or the end of the text.
Since the line number is entered by the user you should use int.TryParse to handle invalid input.
private void button1_Click(object sender, EventArgs e)
{
int lineNumber;
if (!int.TryParse(textBox2.Text, out lineNumber) || lineNumber < 0)
{
textBox1.Select(0, 0);
return;
}
int position = textBox1.GetFirstCharIndexFromLine(lineNumber);
if (position < 0)
{
// lineNumber is too big
textBox1.Select(textBox1.Text.Length, 0);
}
else
{
int lineEnd = textBox1.Text.IndexOf(Environment.NewLine, position);
if (lineEnd < 0)
{
lineEnd = textBox1.Text.Length;
}
textBox1.Select(position, lineEnd - position);
}
}
Apply this logic to your code, and recode it as you need.
private void button1_Click(object sender, EventArgs e)
{
if (textBox_Form1.Text.Contains(textBox_Form2.Text))
{
textBox_Form1.Focus();
textBox_Form1.SelectionStart = textBox_Form1.Text.IndexOf(textBox_Form2.Text);
textBox_Form1.SelectionLength = textBox_Form2.Text.Length;
}
}
try something like;
int lineNumber = Form1.ab;
// split the contents of the text box
string text = textBox1.Text;
string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
if (lineNumber < 0 || lineNumber > lines.Length)
{
MessageBox.Show("The line number is does not exist");
return;
}
// get the character pos
int selStart = 0;
for (int i = 0; i < (lineNumber - 1); i++)
{
selStart += lines[i].Length + Environment.NewLine.Length;
}
textBox1.Focus();
textBox1.SelectionStart = selStart;
textBox1.SelectionLength = lines[lineNumber - 1].Length;
Note: you can access the other text box directly in the other form by going to the Form2 designer, clicking the text box and going to Properties. In the Properties dialog, look for a property called Modifiers and change the value to internal or public. This will allow you to access the text box value in the other form directly like so;
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2Instance = new Form2();
string sampleText = form2Instance.textBox1.Text;
}
If you need to know further samples on how to access controls/details on other forms, let me know.
You are creating a NEW form1 where the textbox is likely to be blank, and calling GetPass() on that empty form. You need an instance of the already-opened form1 where the textbox might have a value. for more information
click here
Try the below code
var sdr = (System.Windows.Controls.TextBox) sender;
if (!string.IsNullOrEmpty(sdr.Text)) {
var start = sdr.Text.LastIndexOf(Environment.NewLine, sdr.CaretIndex);
var lineIdx = sdr.GetLineIndexFromCharacterIndex(sdr.CaretIndex);
var lineLength = sdr.GetLineLength(lineIdx);
sdr.SelectionStart = start + 1;
sdr.SelectionLength = lineLength;
sdr.SelectedText.Substring(0, sdr.SelectedText.IndexOf(Environment.NewLine) + 1);
Clipboard.SetText(sdr.SelectedText);
}
maybe this better:
{
...
string SelectedText = fr.textBox1.Lines[line];
int SelectedTextPos = fr.textBox1.Text.IndexOf(SelectedText);
int SelectedTextLen = SelectedText.Lenght;
fr.textBox1.Select(SelectedTextPos, SelectedTextLen);
fr.textBox1.ScrollToCaret();
...
}

Categories