Adding textbox value, stay high value - c#

Goal: The value I enter in the first box will be written in the second box
Goal: The second textbox will always write the highest value even if the first textbox changes
private void ModuleltextBox_TextChanged(object sender, EventArgs e)
{
try{
secondTxt.Text = firstTxt.Text;
var y = int.Parse(secondTxt.Text);
var x = int.Parse(firstTxt.Text);
if (y >= x)
{
//??
}
else if(x<y)
{
//??
}
}
catch (Exception){
}

You just need to set the Text property after comparing both text boxes value like :
try
{
var y = int.Parse(secondTxt.Text);
var x = int.Parse(firstTxt.Text);
if (y < x)
{
secondTxt.Text = x.ToString();
}
else
{
secondTxt.Text = y.ToString();
// or probably this line is not needed as y is already set in second TextBox
}
if first text box value is greater it will get set in secondTextBox otherwise the secondTextBox already have highest value.

I would think something like this would suffice?
private void ModuleltextBox_TextChanged(object sender, EventArgs e)
{
int x, y;
if (int.TryParse(firstTxt.Text, out x) && int.TryParse(secondTxt.Text, out y))
{
secondTxt.Text = Math.Max(x, y).ToString();
}
}

Put this piece of code in your textbox1 TextChanged event.
try
{
textBox2.Text = textBox1.Text;
int firstnum = int.Parse(textBox1.Text);
int secondnum = int.Parse(textBox2.Text);
}
catch
{
}
I think your second goal is not possible if you're using a TextChanged event since every changes you'll made in TextBox1 will be also made in TextBox2.

Related

How to get text of NumericUpDown before valuechanged event?

I want to make it work this way: when I write to NumericUpDown 1k the value should be 1000, when I write 4M the value should be 4000000. How can I make it?
I tried this:
private void NumericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyValue == (char)Keys.K)
{
NumericUpDown1.Value = NumericUpDown1.Value * 1000;
}
}
But it works with the original value that I wrote.
I want to make it work as a macroses. For example, If I want to get NUD1.Value 1000, I write 1 and then, when I press K the NUD1.Value becomes 1000.
Let's assume we have a NumericUpDown named numericUpDown1. Whenever the user presses k, we want to multiply the current value of the NUP by 1,000, and if the user presses m, the current value should be multiplied by 1,000,000. We also don't want the original value to trigger the ValueChanged event. So, we need to have a bool variable to indicate that the value is being updated.
Here's a complete example:
private bool updatingValue;
private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData != Keys.K && e.KeyData != Keys.M) return;
int multiplier = (e.KeyData == Keys.K ? 1000 : 1000000);
decimal newValue = 0;
bool overflow = false;
try
{
updatingValue = true;
newValue = numericUpDown1.Value * multiplier;
}
catch (OverflowException)
{
overflow = true;
}
updatingValue = false;
if (overflow || newValue > numericUpDown1.Maximum)
{
// The new value is greater than the NUP maximum or decimal.MaxValue.
// So, we need to abort.
// TODO: you might want to warn the user (or just rely on the beep sound).
return;
}
numericUpDown1.Value = newValue;
numericUpDown1.Select(numericUpDown1.Value.ToString().Length, 0);
e.SuppressKeyPress = true;
}
And the ValueChanged event handler should be something like this:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (updatingValue) return;
// Simulating some work being done with the value.
Console.WriteLine(numericUpDown1.Value);
}

Same custom set property for some class field

I want every time that TextBox filed is set the back color change according to the sign.
public TextBox Current_value_text1
{
get { return Current_value_text; }
set {
Current_value_text = value;
if (Current_value_text.Text[0] == '+')
Current_value_text.BackColor = Color.Green;
else
Current_value_text.BackColor = Color.Red;
}
}
but I want to do this for all my textbox fields - any suggestions?
Thanks
You are probably looking for TextChanged event: whenever TextBox(es) change its Text, analyze it and update BackColor when necessary.
If it's your case, can select all the Textboxes (say, with a mouse), open "Properties" window and implement event hander for the TextChanged:
private void myTextBox_TextChanged(object sender, EventArgs e) {
TextBox box = sender as TextBox;
if (null == box)
return;
box.BackColor = box.Text.Trim().StartsWith("-")
? Color.Red
: Color.Green;
}
EDIT: The question in the comment is a quite different case; here we don't have events, but we can try extracting a method (NumSet):
private int m_Num1;
private int m_Num2;
private void NumSet(ref int num, int value) {
if (value == 1)
num = value + 1;
else
num = value - 1;
}
public int Num1 {
get => m_Num1;
set => NumSet(ref m_Num1, value);
}
public int Num2 {
get => m_Num2;
set => NumSet(ref m_Num2, value);
}

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();
...
}

converting textbox string to int

I'm trying to compare and multiply 2 random number variables with the int value entered in textboxes. If it is the correct increment the correct answers it does not increase the number although it increment works alone but it does not work with the textbox.
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
int s = x * z;
if (s == int.Parse(textBox4.Text))
{
correct++;
numbercorrect.Text = correct.ToString();
}
}
EDIT This is assuming that you are trying to have the user enter their guess before the button is pressed. Figured I would put this disclaimer here since there is confusion exactly what you are trying to do.
Looking at your current code sample, you are trying parse textBox4.Text, however, you are not setting textBox4.Text anywhere in your code sample. If textBox4.Text is string.Empty, int.Parse will throw an exception.
You should also look into doing Int.TryParse as it will tell you if it worked without throwing an exception.
EDIT: Since this is a guessing game, you should be validating the user's entry in textBox4 before continuing.
private void button1_Click(object sender, EventArgs e)
{
int answer;
if(!int.TryParse(textBox4.Text, out answer))
{
MessageBox.Show("Please Enter A Valid Integer.");
return;
}
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
int s = x * z;
if (s == answer)
{
correct++;
numbercorrect.Text = correct.ToString();
}
}
You're comparing the textbox value to the product of two random values. Unless you know what those two random numbers are before you push the button, the if will fail.
This subroutine will be run as soon as Button1 is pressed. This will display two random numbers for the user to multiply. (Displayed in TB2 and TB3.)
Now, as soon as these numbers are displayed (and before the user has a chance to enter any answer) the program checks the value in TB4. This is empty, and throws an error when the parse is attempted.
Try breaking this into 2 subroutines with 2 buttons: one button to display a new problem, and one button to check the answer.
EDIT: Code added. (Note: I wrote this freehand--don't know if it would compile or not... just get the general idea. Note the button names.)
//This routine sets up the problem for the user.
private void btnGenerateProblem_Click(object sender, EventArgs e) {
//Get 2 random factors
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//Display the two factors for the user
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
}
//This routine checks the user's answer, and updates the "correct count"
private void btnCheckAnswer_Click(object sender, EventArgs e) {
//Get the random numbers out of the text boxes to check the answer
int x = int.Parse(textBox2.Text);
int z = int.Parse(textBox3.Text);
//Compute the true product
int s = x * z;
//Does the true product match the user entered product?
if (s == int.Parse(textBox4.Text)) {
correct++;
numbercorrect.Text = correct.ToString();
}
}
Add verification code at the beginning of btnCheckAnswer_Click.
private void button1_Click(object sender, EventArgs e)
{
int result = Convert.ToInt32(textBox4.Text); int x, z;
if (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text) == result)
{
correct++;
numbercorrect.Text = correct.ToString();
Randomnumber.Next(12);
textBox2.Text = Randomnumber.Next(12).ToString();
textBox3.Text = Randomnumber.Next(12).ToString();
}
}

c# winForm adding value to number in texbox

In my program i have several texboxes and buttons with coresponding names (ex. TextBox1 - buttonPlus1) like on the picture
but there are filled with numbers loaded from text file.
I want to write function that allows me to press button + and enlarge (add fixed number, for example 100) value from textbox. So far i have done:
private void buttonPlus1_Click(object sender, EventArgs e)
{
AddValue(sender,e);
}
private void AddValue(object sender, EventArgs e)
{
if (!(sender is Button))
return;
string controlName = (sender as Button).Name;
string textBoxName = controlName.Replace("buttonPlus", "textBox");
TextBox textBox = this.Controls.Find(textBoxName, false)[0] as TextBox;
int step = 100;
}
but i have no idea how to take value (as number) from textBox and add that step. Can somebody please help me? I tried to solve it by myself in many different ways, but it does not work
Get the value:
Convert.ToInt32(textBox.Text)
Save it to a variable, add 100 and just set it as usual.
P.S. You can also use Int32.Parse("")
textBox.Text = Convert.ToInt32(textBox.Text) + 100;
(You might need to .ToString() it)
EDIT:
As ltiong_sh mentioned, you should use TryParse rather then Parse:
int somevalue;
if(Int32.TryParse(textBox.Text, out somevalue))
{
textBox.Text = somevalue + 100;
}
You need to convert String to Integer
int txtValue = Convert.ToInt32(textBox.Text) + 100;
Make sure your validate the text in the text field. Else at the time of parsing it will throw an exception.
You can do this
int value = 0;
if(Int32.TryParse(textBox.Text, out value))
{
value += step;
textBox.Text = value.ToString();
}
else
{
//inform user to enter int
}
This is what you are looking for:
int newValue = Convert.ToInt32(textBox.Text) + step;
To put the value back in a textbox you can do the following:
textBox.Text = newValue.ToString();
Edit:
As mentioned by others you should use Int32.TryParse to prevent an error from being thrown.
if(Int32.TryParse(textBox.Text, out newValue))
{
newValue += step;
textBox.Text = newValue.ToString();
}
in button click get the textbox value and convert it to integer format and add 100 to it. after that reset textbox value to modified one's. Here is what you need.
private void buttonPlus1_Click(object sender, EventArgs e)
{
try
{
int txtValue = Convert.ToInt32(textBox.Text) + 100;
textBox.Text = txtValue.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

Categories