Auto formatting a textbox text - c#

I want to auto format a text entered in a textbox like so:
If a user enters 2 characters, like 38, it automatically adds a space. so, if I type 384052
The end result will be: 38 30 52.
I tried doing that, but it's ofr some reason right to left and it's all screwed up.. what I'm doing wrong?
static int Count = 0;
private void packetTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
Count++;
if (Count % 2 == 0)
{
packetTextBox.Text += " ";
}
}
Thanks!

It's much nicer if you just let the user type and then modify the contents when the user leaves the TextBox.
You can do that by reacting not to the KeyPress event, but to the TextChanged event.
private void packetTextBox_TextChanged(object sender, EventArgs e)
{
string oldValue = (sender as TextBox).Text.Trim();
string newValue = "";
// IF there are more than 2 characters in oldValue:
// Move 2 chars from oldValue to newValue, and add a space to newValue
// Remove the first 2 chars from oldValue
// ELSE
// Just append oldValue to newValue
// Make oldValue empty
// REPEAT as long as oldValue is not empty
(sender as TextBox).Text = newValue;
}

On TextChanged event:
int space = 0;
string finalString ="";
for (i = 0; i < txtbox.lenght; i++)
{
finalString = finalString + string[i];
space++;
if (space = 3 )
{
finalString = finalString + " ";
space = 0;
}
}

I used
int amount;
private void textBox1_TextChanged(object sender, EventArgs e)
{
amount++;
if (amount == 2)
{
textBox1.Text += " ";
textBox1.Select(textBox1.Text.Length, 0);
amount = 0;
}
}

Try this..
on TextChanged event
textBoxX3.Text = Convert.ToInt64(textBoxX3.Text.Replace(",", "")).ToString("N0");
textBoxX3.SelectionStart = textBoxX3.Text.Length + 1;

Related

How to add space between bytes in textbox?

I have one textbox which gets only bytes and I want to add space between every bytes.
What I have done so far?
public int a=0;
public char c;
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
c = e.KeyChar;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
a = textBox2.TextLength % 3;
if (c != 0x08 && a==2)
{
a = textBox2.TextLength % 3;
int selectionIndex = textBox2.SelectionStart;
textBox2.Text = textBox2.Text.Insert(selectionIndex, " ");
textBox2.SelectionStart = selectionIndex + 1; // restore cursor position
}
}
I add space with this code but if I delete some bytes it doesn't add space.
I think there is some issue in 'if' condition.
For example I write 'abcdef' it adds space and write
ab cd ef
then I delete 'cdef' and space it works properly in here.
I write again 'cdef' it doesn't work and result will be like that
abcde f
How can I fix this issue?
I solve the problem with this code.
private void textBox5_TextChanged(object sender, EventArgs e)
{
int selectionIndex = textBox5.SelectionStart;
int chars = textBox5.Text.Length;
int a = chars % 3;
if (a == 2 && c!=0x08)
{
textBox5.Text = textBox5.Text.Insert(selectionIndex, " ");
textBox5.SelectionStart = selectionIndex + 1; // restore cursor position
}
if (chars > 1)
{
if (a == 0 && c == 0x08)
{
textBox5.Text = textBox5.Text.Remove(chars - 1);
textBox5.SelectionStart = selectionIndex + 1;
}
}
}

Insert data in RichTextBox C#

My code:
private void timer4_Tick(object sender, EventArgs e)
{
for (int a = 0; a < 10; a++)
{
var infos = webBrowser1.Document.GetElementsByTagName("img")[a].GetAttribute("src");
richTextBox1.Text = infos;
}
timer4.Stop();
}
I want to insert all of 10 src values in RichTextBox, while my code do it only once.
You can use AppendText
Replace
richTextBox1.Text = infos;
with
richTextBox1.AppendText(infos);
OR
richTextBox1.Text += infos + Environment.NewLine;
This line is wrong.
richTextBox1.Text = infos;
This is right.
richTextBox1.AppendText= infos;
What your code is doing is setting the text to equal each infos, 10 times over.
So I'm guessing your output would be the last infos variable? What you might want to do instead is this:
private void timer4_Tick(object sender, EventArgs e)
{
for (int a = 0; a < 10; a++)
{
var infos = webBrowser1.Document.GetElementsByTagName("img")[a].GetAttribute("src");
richTextBox1.Text += infos; // the "+=" will add each infos to the textbox
}
timer4.Stop();
}
As you can see, if you use the += instead of just =, it will add each iteration to the whole, instead of just overriding the whole value each time.

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";

Not able to count line number in richtextbox

here is my code
private void Allocation_Matrix_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
int Total_Row_Check;
Total_Row_Check = getRow();
Textbox1.Text = Convert.ToString(Total_Row_Check);
if (Total_Row_Check >= Convert.ToInt32(Total_Processes.Text))
{
MessageBox.Show("rows cannot exceed from total number of processess");
}
}
}
public int getRow()
{
int Row = 0;
string[] arLines;
int i;
arLines = Allocation_Matrix.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
for (i = 0; i < arLines.Length; i++)
{
Row++;
}
return Row;
}
i want to update TextBox1 as i hit ENTER in richtextbox from keyboard...but Textbox keeps show only FirstRow and shows One(1)
How about using RichTextBox.GetLineFromCharIndex Method? It returns, the zero-based line number in which the character index is located.
Is Allocation_Matrix your RichTextBox?
Note that RichTextBox.Text returns the text with line feed ("\n") for the line breaks, where most all other Windows controls use a carriage return, line feed ("\r\n").
So if you are calling Split on the string returned by the Text property, it won't contain any Evironment.NewLine.
try Allocation_Matrix.Text.Lines.Count() method
try this
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
var lineCount = richTextBox.Lines.Count();
numberLabel.Text = lineCount.ToString();
}

Concatenate hex numeric updowns to string for a textbox

I have 4 numeric up down controls on a form. They are set to hexidecimal, maximum 255, so they'll each have values from 0 to FF. I'd like to concatenate these values into a string for a textbox.
You can do something like the following
textBox1.Text = string.Format("{0:X2}{1:X2}{2:X2}{3:X2}",
(int)numericUpDown1.Value,
(int)numericUpDown2.Value,
(int)numericUpDown3.Value,
(int)numericUpDown4.Value);
Assuming you gave the NUDs their default names:
private void button1_Click(object sender, EventArgs e) {
string txt = "";
for (int ix = 1; ix <= 4; ++ix) {
var nud = Controls["numericUpDown" + ix] as NumericUpDown;
int hex = (int)nud.Value;
txt += hex.ToString("X2");
}
textBox1.Text = txt;
}

Categories