How to make text display in a textbox multiple times in C#? - c#

I want to display something multiple times in a textbox. For example if you use this code and replace richtextbox with messagebox, it will keep displaying the text until the loop ends. I want to display the text from textBox1 into richTextBox1, and then have the program hit enter, and then type it out again in the richtextbox. It's kind of confusing sorry, but if you have any questions just comment them and i'll be more clear. This is my code:
private void button1_Click(object sender, EventArgs e)
{
Clipboard.SetText(textBox1.Text);
int text = 0;
int end = int.Parse(textBox2.Text);
while (text<=end)
{
richTextBox1.Text=(Clipboard.GetText());
text++;
}
Thanks in advance!

In your code you have:
richTextBox1.Text=(Clipboard.GetText());
The reason that your code is not working is because in every loop, you are setting the text to whatever is on the clipboard, so at the end of the loop it will only have it in there once. You need to 'append' or add onto the end of the text so it will have it multiple times:
richTextBox1.Text += richTextBox1.Text + (Clipboard.GetText());
Or:
richTextBox1.Text += (Clipboard.GetText());
This will add the clipboard text onto the end of the RichTextBox, so you will have the same text multiple times, but all on the same line. If you want to make the text appear on multiple lines, you have to add a new line after appending the text:
richTextBox1.Text += (Clipboard.GetText())+"\r\n";
Or:
richTextBox1.Text += (Clipboard.GetText())+Enviroment.NewLine;
Hope this Helps!

Use Timer instead of using loop and keep its interval time like for 2 second. and on button click start timer and declare end as class variable , when condition is met for "end" variable , stop timer.
private void button1_Click(object sender, EventArgs e)
{
end = int.Parse( textBox2.Text);
timer1.Start();
}
private int end = 0;
private int start = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (start == end)
{
timer1.Stop();
}
else
{
start++;
textBox1.Text = start.ToString();
}
}

Related

Program for learning foreign words C#

I am in the process of writing a vocabulary program. C # Windows Form.
Description of the program operation:
Use the buttons to select the location of text files with the words "PL" and "ENG". (two separate files)
Click the start button to start the program
the first word from the board appears in the label
I'm translating the word into the textbox and the Messagebox "OK" or "WRONG" pops up
And here a problem arises. The program instead of every time I wait until I introduce a new word to the textbox, it loops, the questions in the label are changed and MessageBox displays.
How best to do this to make the program work correctly? `` `[
private void sprawdzButton_Click(object sender, EventArgs e)
{
BazaSlow.bazaPolskichSlowek = _fileReader.Read(adresPlikuPL);
BazaSlow.bazaAngielskichSlowek = _fileReader.Read(adresPlikuANG);
string odpowiedz = odpTextBox.Text;
int i = 0;
while (i < BazaSlow.bazaPolskichSlowek.Length)
{
trescSlowkaLabel.Text = BazaSlow.bazaPolskichSlowek[i];
if (odpowiedz.Equals(BazaSlow.bazaAngielskichSlowek[i].ToLower()))
{
MessageBox.Show("OK");
}
else
{
MessageBox.Show("ŹLE");
}
i++;
}
}
This approach will not quite work.
If you use WinForms then you can do it via events. I'll quickly use english variable names since I don't speak your language.
This could be one approach to do it: I used the "TextChanged" event from the textBox.
string[] wordsLanguage1;
string[] wordsLanguage2;
int currentIndex = 0;
private void Form1_Load(object sender, EventArgs e)
{
wordsLanguage1 = System.IO.File.ReadAllLines("somePath1");
wordsLanguage2 = System.IO.File.ReadAllLines("somePath2");
}
private void ReportAndCheckInput(string input)
{
if (input.ToLower().Equals(wordsLanguage2[currentIndex].ToLower())) {
//right translation
currentIndex++;
label1.Text = wordsLanguage1[currentIndex];
textBox1.Text = "";
}
else
{
//wrong translation
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
ReportAndCheckInput(textBox1.Text);
}
Now this approach uses the TextChanged event. So the ReportAndCheckInput method will be called on every text-change. That means that your Feedback would pop up on every keystroke which would not be nice. You could use any other event instead of TextChanged. For example a button click. Another solution would be to use a label for your feedback and not a message box. Then the user would never have to click anything but woudl instantly see whether or not he was correct.

Add character every 2 characters entered to textbox Windows Phone 8

Hi i want to make textbox to enter mac adress and every 2 characters i want to automaticly add ':'
I wanted to use TextChanged event
private void MacAdressTextBox_TextChanged(object sender, TextChangedEventArgs e) {
if (MacAdressTextBox.Text.Length > 2)
MacAdressTextBox.Text += ":";
}
here i am adding : after 2 characterrs entered but after those 2 characters the app frezes ... have no idea why any help?
When the text changes MacAdressTextBox_TextChanged is triggered.
In MacAdressTextBox_TextChanged you change the text.
see step 1
your text change causes an infinite recursion on MacAdressTextBox_TextChanged.
One way to do it would be to grab the Text, remove the colons, then add them back in at the correct positions. In order to keep the app from hanging in an endless recursive loop, you can add a variable to track whether or not the text is being changed by our code or the user.
For example:
// When this is true it means our code is changing the text
private bool updatingTextWithCode = false;
private void MacAdressTextBox_TextChanged(object sender, EventArgs e)
{
if (updatingTextWithCode)
{
// Our code is doing the update, so just reset the variable
updatingTextWithCode = false;
}
else
{
// The user is updating the text, so process the contents
var newText = "";
// Store the mac address without the ':' characters
var plainText = MacAdressTextBox.Text.Replace(":", "");
// Then add ':' characters in correct positions to 'newText'
for (int i = 1; i <= plainText.Length; i++)
{
newText += plainText[i - 1];
if (i % 2 == 0) newText += ":";
}
// Set our global variable and update the text
updatingTextWithCode = true;
MacAdressTextBox.Text = newText;
MacAdressTextBox.Select(MacAdressTextBox.TextLength, 0);
}
}
UPDATE: CodeCaster correctly pointed out that this code does not allow the user to backspace over a colon. One way to fix this is to add the following event handler as well:
private void MacAdressTextBox_KeyDown(object sender, KeyEventArgs e)
{
// Disable formatting code when backspacing
if (e.KeyCode == Keys.Back) { updatingTextWithCode = true; }
}

My form doesn't loop this correctly

I can't seem to get this loop to work.
Once the submit button is clicked ten times it should revert to the main form; instead it's reverting as soon as the submit is clicked once.
private void submit_Click(object sender, EventArgs e)
{
Form1 mainMenu = new Form1();
int repeat = 0;
do
{
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A1.secondRandomNumber().ToString();
repeat++;
} while (repeat <= 10);
if (repeat == 11)
{
mainMenu.Show();
this.Hide();
}
}
Everything inside of submit_Click occurs for each click. That includes defining repeat anew, setting it to 0, looping to increment it entirely to 11, and swapping which form is visible.
If you want to count the number of clicks, you'll have to establish your counter outside of the handler so it can be incremented:
private int repeatSubmit = 0;
private void submit_Click(object sender, EventArgs e)
{
if (repeatSubmit < 10)
{
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A1.secondRandomNumber().ToString();
repeatSubmit++;
}
else
{
mainMenu.Show();
this.Hide();
repeatSubmit = 0; // ready for the next time `this` form is shown
}
}
Just to clarify, you are waiting for the user to click the button 10 times? Or the loop is supposed to simulate 10 clicks?
This loop will enter (do) and set num1 and num2, add one to repeat, and then do that 10 times until repeat == 11, and then it will display the main menu.
I think the code you make be looking for is as follows:
private void submit_Click(object sender, EventArgs e)
{
...
repeat ++;
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A2.secondRandomNumer().ToString();
if(repeat >=10)
{
mainMenu.Show();
this.Hide();
}
}
As your code is, on 1 click you enter your loop where you proceed to increment the counter until it's equal to 11, then you exit your loop and show the main menu. Basically you're not counting clicks.
What you want to do is store the counter somewhere, probably as a class variable. Then every time you enter the click function you increment. When the click function has been entered 10 times then you would go into your if statement.
private int clickCount = 0;
private void submit_Click(object sender, EventArgs e){
clickCount++;
// Other code that happens on a click
if (clickCount == 10){ // 10th click show main menu
// Code to show main menu
}
}
It runs through the loop on the first click of submit, if I understand what you are trying to achieve, you don't need a loop at all, just a counter for each time the button is pressed.

Auto refresh labels as text boxes text input data into method

Here is my method that I' am trying to have automatically refresh my label. When I have my label as a click event...the answer refreshes and is correct.
private void Calculate()
{
dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
double UtilRounded1 = Math.Round(dblUtil1 * 100);
strUtil1 = UtilRounded1.ToString() + "%";
}
Here is the Validated label event that does not update when text is changed in my text boxes.
private void lblUtil1_Validated(object sender, EventArgs e)
{
Calculate();
}
If this is correct...what am I missing? is there something I need to do on the text boxes that will trigger validation?
I have also tried a text changed event that yields the error cannot implicitly convert type void(or any type for that matter) to EventHandler. Here is the code.
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
lblUtil1.TextChanged += Calculate();
}
Any help is appreciated! I've been banging my head on my keyboard for a day now.
First at all, you have to handle events for the TextBox that you input value to calculate, such as when you change vale in the TextBox or validate it.
So if you have textBox1 then you should have this handling (trigger when value in textBox1 is changed)
private void textBox1_TextChanged(object sender, EventArgs e)
{
lblUtil1.Text = Calculate();
}
I assume that you want to display value in strUtil1 at the label lblUtil1, so you have to change your Calculate method like this
private string Calculate()
{
dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
double UtilRounded1 = Math.Round(dblUtil1 * 100);
strUtil1 = UtilRounded1.ToString() + "%";
return strUtil1;
}
EDITED
This is a sample code for validate the required TextBoxes.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == "")
{
e.Cancel = true;
lblUtil1.Text = "textBox1 is required!";
}
}
Try calling yourlabelname.Refresh() i.e like
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
lblUtil1.TextChanged = Calculate();
lblUtil1.Refresh();
}
or
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
Calculate();
lblUtil1.Refresh();
}
You need to do a couple things.
First, stop using "hungarian" notation. It's bad. It's bad for a lot of reasons. MS even says, "don't use hungarian" as most people get it wrong as your code shows. Instead, name your variables appropriately. For example, dblSG has absolutely zero meaning.
Second, please reread Michael's answer to your question from yesterday ( https://stackoverflow.com/a/20026642/2424 ). He did NOT say to use lblUtil1_Validated. He said to use TextBox_Validated. In other words, the event you should have your calculation run on is with the textbox fields on your form. He also suggested you just use the textboxes TextChanged events in order to cause the calculation to run as they are typing. Personally, I don't agree with that but whatever.
A third possible option is to simply go back to your original solution. Meaning, just run the calculation when the label is clicked. In which case you should refer back to your original question as Michael failed to answer it.

RichTextBox caret position when inserting rtf string

I am trying to insert rtf string into a RichTextBox. This is the KeyUp event form RichTextBox:
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
string st = richTextBox1.Rtf;
st=st.Insert(750, "void");
richTextBox1.Rtf = st;
}
The problem is that, after each update, the caret goes before the inserted text and I want to keep it at the end. I noticed that this is happening only when I modify the length of st.
I can't fathom how your code is supposed to work for the end user. How would you even know that at index 750 you have text versus an rtf control character?
The quick solution is to just set the caret position to the end yourself:
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
string st = richTextBox1.Rtf;
st=st.Insert(750, "void");
richTextBox1.Rtf = st;
richTextBox1.SelectionStart = richTextBox1.TextLength;
}
Of course, if you are trying to put the caret at the position where void is inserted, that wouldn't work with your rtf property, since the rtf and text properties are different things.
If trying to insert text in the text property, then it would look something like this:
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
string st = richTextBox1.Text;
st=st.Insert(750, "void");
richTextBox1.Text = st;
richTextBox1.SelectionStart = 750 + 4;
}

Categories