TextBox text "Replace" function does not work well - c#

I have already looked at similar questions here but it did not help.
I am using windows forms. I have button1 and textbox1.
I am trying to replace (or delete) the selected text in textBox1 and enter new letter (letter A) in place of it.
The code works well with random mixed numbers and letters
for example:
385F1 select 8 and then result = 3A5F1 (8 replaced by A)
H74S31B select 4S and then the result is = H7A31B
KQ5689 select Q5689 and then the result is KA
So it works well, but when I select a number or a letter from a string which consists of same numbers or letters then it does not work, for example:
666777222333 select any 7 then the result = 666AAA222333 (not
working)
9992244GG select any 9 then the result = AAA2244GG (not working)
QQQHHHUUU select any Q then the result = AAAHHHUUU (not working)
QQQHHHUUU select any QH then the result = QQAHHUUU(it works when
different letters selected)
4433366 select 333 then the result = 44A66 (it works when all same
numbers is selected)
Hope I explained it well. I don't know what causes this behavior. please help. Thank you
public partial class Form1 : Form
{
int TxTindex;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ActiveControl = textBox1;
textBox1.Focus();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Focus();
if (textBox1.SelectedText.Length > 0) // to check if any text selected
{
TxTindex = textBox1.SelectionStart; // save the caret position
textBox1.Text = textBox1.Text.Replace(textBox1.Text.Substring(textBox1.SelectionStart, textBox1.SelectionLength),"A");
textBox1.SelectionStart = TxTindex + 1; // place the caret after the inserted string
}
else
{
return;
}
}
}

Your problem is here :
textBox1.Text = textBox1.Text.Replace(textBox1.Text.Substring(textBox1.SelectionStart, textBox1.SelectionLength),"A");
The Substring function returns string. In your example (666777222333 select any 7 then the result = 666AAA222333 (not working)), it returns "7". But Text.Replace will replace all occurrences of 7. That is not what you want. What you can do is, instead of using string.Replace function, use string.Remove and string.Insert
textBox1.Text = textBox1.Text.Remove(textBox1.SelectionStart, textBox1.SelectionLength).Insert(textBox1.SelectionStart, "A");
But this might not be very efficient for large strings. A StringBuilder would be better.

The problem is caused by the usage of string.Replace function.
What you are trying to accomplish can be done simply by
if (textBox1.SelectionLength > 0)
textBox1.SelectedText = "A";
There is no need to save/set selection start.

Related

How to automatically lower case the 2nd letter of a word in a WPF textbox?(C#)

I am trying to create a function which automatically lower cases the 2nd Letter of a Word
in a textbox. I already tried it with this function but i ran into one problem:
After the function detects a 2nd letter of a word which isn't written in lower case it sets the letter to capital. But after that the writing cursor moves to the beginning of the textbox. (the cursor moves in front of the already written words)
private void Text1_KeyDown(object sender, KeyEventArgs e)
{
string erg;
string input;
input = Convert.ToString(Text1.Text);
if (input.Length > 1)
{
erg = input[0] + input.Substring(1, 1).ToLower() + input[2..];
Text1.Text = erg;
}
}
Thank You in advance!
You need to remember and then set the CaretIndex to the correct position, like so
var originalIndex = Text1.CaretIndex;
// Your code
Text1.CaretIndex = originalIndex;
well you can just do this
var secondChar = text[1].ToString();
var loweredString = text[0] + secondChar.ToLower() + text[2..];
and set loweredString to your textBox.

c# replace string with many "x" [duplicate]

This question already has answers here:
Best way to repeat a character in C#
(21 answers)
Closed 1 year ago.
I am writing a windows form app in C#. I have a label with a random word, e.g. "computer". User has to guess what is this word by guessing letter by letter. But word "computer" must be replaced with as many "x" as there is letters in a word, so in this example user should see "xxxxxxxx".
I tried to replace it with regex like this:
private void Form1_Load(object sender, EventArgs e)
{
word.Text = Regex.Replace(word.Text, #"^[a-zA-Z]+$", "x");
}
But it only replace with single "x".
I also tried with for loop, but the result is the same:
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <= word.Text.Length; i++)
{
word.Text = Regex.Replace(word.Text, #"^[a-zA-Z]+$", "x");
}
}
You can create a new string of "x" repeated the number of characters in your word. No need for regexes.
word.Text = new string('x', word.Text.Length);
Approach without RegEx
string wordText = "computer";
wordText = string.Concat(wordText.Select(x => char.IsLetter(x) ? 'x' : x));
if you want to stay with RegEx, replace #"^[a-zA-Z]+$" with "[a-zA-Z]" to match every single character
Try this:
word.Text=String.Join("",word.Text.Select(s=>s='x').ToArray());

populating empty field of a string with 0(zero) in c# winform?

I have a winform where I have a textbox that will take upto 14 numbers. Now if user enters less that 14 i have to populate the rest of the fields with 0s. Eg. if a user 10 numbers the i have to include 4 more 0's to to make it 14.
Change the MaxLength property of the text box to 14. After you get the Text property, use, the PadLeft, or PadRight methods on the String class.
Example
void textBox_LostFocus(object sender, EventArgs e)
{
var text = this.textBox.Text;
text = text.PadLeft(14, '0');
this.textBox.Text = text;
}
Results
var value = "abcd";
var leftPadded = value.PadLeft(14, '0'); // <- "0000000000abcd"
var rightPadded = value.PadRight(14, '0'); // <- "abcd0000000000"
You might also want to consider using the MaskedTextBox class.
textbox.TextChanged += new EventHandler( textbox_TextChanged );
private textbox_TextChanged(Object sender, EventArgs e) {
textbox.Text = textbox.Text.PadLeft(14, '0');
}
If you use databinding, and if you just want to add the numbers in the display of the textbox, and not in the underlying datasource, you can use standard .net formatting when you create your own textbox derivative, as described here. Might come in handy.

Select Text in a multiline textbox, move it to another multiline textbox on a button click in C#

I have a problem that I haven't come across yet that I hope some of you may help me with. I am trying to select a single line, either the fist, second, or last line in a multiline textbox and move it to another multiline textbox with a button click in C#. I am unsure how to select just a single line at a time, then add it to the other multiline textbox. If anyone has some insight, that would be great! Thank you!
Brent
Well, assuming that you are defining a "line" as a complete string of characters separated by other similar strings with a newline character, and not simply as the string of characters visible in a single horizontal plane in a text field with word wrap property set to true.....
public void Button1_Click(object sender, ClickEventArgs e)
{
//get the values of both boxes
string value1 = TextBox1.Text.Trim();
string value2 = TextBox2.Text.Trim();
//split the value from the source box on its new line characters
string[] parts = value1.split(Environment.NewLine);
string last_line = parts[parts.length -1];
//add the last row from the source box to the destination box
value2 += (Environment.NewLine + last_line);
//set the last_line in the source to an empty string
parts[parts.Length -1] = String.Empty;
//put the new values back in their text boxes
TextBox1.Text = String.Join(Environment.NewLine, parts).Trim();
TextBox2.Text = value2;
}
If you are dealing with visible line and word wrapped that is a whole 'nother ball game and the answer is dependant on if you are talking ASP, or Win App. Also, this was written off the cuff, so you may need to tweak a character or two to get it to compile. No Warranties, LOL.
Something like this will work:
public void Button1_Click(object sender, ClickEventArgs e)
{
string text = TextBox1.Text;
// spliting text on the basis on newline.
string[] myArray = text.Split(new char[] { '\n' });
foreach (string s in myArray)
{
//Line by line copy
TextBox2.Text += s;
}
}
Try something like this:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Lines.Length > 0)
{
textBox2.Text += textBox1.Lines[textBox1.GetLineFromCharIndex(textBox1.SelectionStart)];
}
}
What it is doing is using the GetLineFromCharIndex with the SelectionStart caret location as the char Index to pull the Line out of the TextBox.Lines array

Simple problem with replacing string value C#

i'm in a bit of a bind with a problem that's supposed to mediocre, but seemingly i can't implement the solution.
I have buttons, with a single char on each of them, 26 to be exact (english alphabet),
When i click any of them, the loop iterates through the string for the text value on the buttons and replaces it with quotation marks.
The code works, and it prints out the newAlphabet without the clicked character. But when i click another button, it returns the newAlphabet albeit with the previously removed character and removes the new clicked character.
The code is as follows
static string alphabet = "abcdefghijklmnopqrstuvwxyz";
static string newAlphabet = string.Empty;
Button tempBtn = (Button)sender;
for (int i = 0; i < alphabet.Length; i++)
{
if (alphabet[i].ToString().Contains(tempBtn.Text))
{
newAlphabet = alphabet.Replace(tempBtn.Text, "");
MessageBox.Show(newAlphabet);
}
}
Sorry for grammar or spelling errors, english is not my first language.
Regards, HC
This line
newAlphabet = alphabet.Replace(tempBtn.Text, "");
means you're always getting back to "abcdefghijklmnopqrstuvwxyz" and replacing that.
If you want to keep replacing letters, you need to replace on newAlphabet.
A simpler solution would be:
static string alphabet = "abcdefghijklmnopqrstuvwxyz";
private void button1_Click(object sender, EventArgs e)
{
var tempBtn = (Button)sender;
alphabet = alphabet.Replace(tempBtn.Text, "");
MessageBox.Show(alphabet);
}
Note 1:
If the code you posted is in your button click event method then it would not compile. In C# you cannot declare variables static inside methods.
Note 2:
Strings are immutable so alphabet.Replace() returns a new string without affecting the original.
If the goal is to remove the clicked letter from the list:
static string newAlphabet = "abcdefghijklmnopqrstuvwxyz";
Button tempBtn = (Button)sender;
newAlphabet = newAlphabet.Replace(tempBtn.Text, "");
MessageBox.Show(newAlphabet);
Please note that strings are immutable in C#. "newAlphabet" is being continuously replaced by a modified "alphabet". It will never stick.

Categories