I'm new to learning winforms and i'm stuck on the following problem and I do not think what I have done is the correct way, so any help would be appreciated.
I have 4 textboxes such as the following
private void txtBxPlayer1Bid_TextChanged(object sender, EventArgs e)
{
txtBxFundsAvialable.Text = (Convert.ToInt32(txtBxFundsAvialable.Text) - Convert.ToInt32(txtBxPlayer1Bid.Text)).ToString();
}
The 5th textbox txtBxFundsAvialable simple subtract the value of txtBxPlayer1Bid from txtBxFundsAvialable.
In designer.cs I have
this.txtBxPlayer1Bid.Leave += new System.EventHandler(this.txtBxPlayer1Bid_TextChanged);
The problem I have is, if I have 100 in txtBxFundsAvialable and enter 10 in txtBxPlayer1Bid the value in txtBxFundsAvialable should be 90, but txtBxPlayer1Bid etc seem to go into a loop and the value in txtBxFundsAvialable becomes 60. 4 textboxes X 10.
This happens for any of the 4 textboxes
The only way I can solve the problem is to set the values of the 4 textboxes to 0 in the txtBxFundsAvialable_TextChanged as shown below.
private void txtBxFundsAvialable_TextChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(txtBxPlayer1Bid.Text) > 4 || (Convert.ToInt32(txtBxPlayer2Bid.Text)> 4 || (Convert.ToInt32(txtBxPlayer3Bid.Text)> 4) || (Convert.ToInt32(txtBxPlayer2Bid.Text)> 4)))
{
txtBxPlayer1Bid.Text = "0";
txtBxPlayer2Bid.Text = "0";
txtBxPlayer3Bid.Text = "0";
txtBxPlayer4Bid.Text = "0";
}
}
Is what I'm doing the correct way, as stated at the beginning, I'm new to winforms and it a canny leanning curve
I wrote a simple code with 2 textboxes that get values and a textbox with the result. Updates with TextChangedevent. Try to use it to fix your code..
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
int num1 = Int32.Parse(textBox1.Text), num2 = Int32.Parse(textBox2.Text);
textBox3.Text = (num1 - num2).ToString();
}
catch { }
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1_TextChanged(sender, e);
}
EDIT
Try this code and link any of your "bid" textboxes to this function. textbox1 in this code is equivalent to your "available" textbox.
private void textBox_Leave(object sender, EventArgs e)
{
try
{
int num = Int32.Parse(((TextBox)sender).Text), available = Int32.Parse(textBox1.Text);
textBox1.Text = (available - num).ToString();
}
catch { }
}
Not sure how .Leave operates. Try to use .TextChanged or whatever the equivalent in WinForms.
All four (or even five) text boxes should use same event callback method.
Here is what you can do in that method:
private void txtBx_TextChanged(object sender, EventArgs e)
{
double player1 = 0, player2 = 0, player3 = 0, player4 = 0, total = 0;
if (int.TryParse(txtBxPlayer1Bid.Text, out player1)
&& int.TryParse(txtBxPlayer2Bid.Text, out player2)
&& int.TryParse(txtBxPlayer3Bid.Text, out player3)
&& int.TryParse(txtBxPlayer4Bid.Text, out player4)
&& int.TryParse(txtBxFundsAvialable.Text, out total)
{
total = player1 + player2 + player3 + player4;
}
}
Related
I have i wpf form with 3 textboxes there i should write how many tickets, then i want to multiply that number with a value
At the end i have another textbox there i want the sum from the 3 textboxes even if only 1 has value
i have tried this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
Cant get it to work
Please help
To convert a string value to an integer value you may use int.Parse method. On the other hand this method (also Convert.ToInt32) requires you making sure that string is always in a good format to get converted. If you are not sure and/or you know that the string may be not in correct format, you may use int.TryParse method, which returns true/false value, stating whether the convert was succesful also giving out required value if it was successful. If it fails you get default value - 0.
If all textboxes follow same procedure you may create only one TextChanged event and bind it to all of them.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int sum = 0;
if (!string.IsNullOrEmpty(textBox1.Text) && int.TryParse(textBox1.Text, out int gold_ticket_count))
{
sum += 120 * gold_ticket_count;
}
if (!string.IsNullOrEmpty(textBox2.Text) && int.TryParse(textBox2.Text, out int silver_ticket_count))
{
sum += 60 * silver_ticket_count;
}
if (!string.IsNullOrEmpty(textBox3.Text) && int.TryParse(textBox3.Text, out int big_show_ticket_count))
{
sum += 500 * big_show_ticket_count;
}
// do smth with the sum...
}
Check if I named textBoxes correctly. It is a good practise to give your controls a meaningful name.
int.Parse doc: https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-6.0
int.TryParse doc: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0
an ugly, quick and dirty but working solution:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int sum1;
private int sum2;
private int sum3;
private int overallSum;
private void tb1_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb1.Text, out int tb1Value))
sum1 = tb1Value * 120;
else
sum1 = 0;
sum_1.Text = sum1.ToString();
RecalcOverallSum();
}
private void tb2_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb2.Text, out int tb1Value))
sum2 = tb1Value * 120;
else
sum2 = 0;
sum_2.Text = sum2.ToString();
RecalcOverallSum();
}
private void tb3_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb3.Text, out int tb1Value))
sum3 = tb1Value * 120;
else
sum3 = 0;
sum_3.Text = sum3.ToString();
RecalcOverallSum();
}
private void RecalcOverallSum()
{
overallSum = sum1 + sum2 + sum3;
overall_sum.Text = overallSum.ToString();
}
}
BTW: I would recommend using MVVM instead of code behind, but I know it wasn't the question
So, I know that with a code snippet such as:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += (x++)%4 + 1;
}
a sequence of 12341234 is displayed on the form if the button is clicked 8 times.
My goal is to get 43214321 to display.
I'm able to get 32103210 with:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 3-(x++)%4;
}
I'm also able to get 32143214 with:
int x = 1; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4 + ;
}
What am I doing wrong? And is there a general formula for this?
Note: My x DOES have to be initialized to 1.
Just change the formula to:
Label1.Text += 4-((x-1)++)%4;
Try using this formula:
5-(1+(x+++3)%4)
That is:
Label1.Text += (5-(1+(x+++3)%4)).ToString();
The first line of code that you've written is basically cycling between 3 to 1.
x=0;
Label1.Text += 3-(x++)%4;
x=0 || Output=3.
Label1.Text= 0+3-(0%4)=3
x=1 || Output=2.
Label1.Text= 0+3-(1%4)=2
x=2 || Output=1.
(Dry run as done above)
x=3 || Output=0.
(dry run as done above)
x=4 and the cycle repeats.
You could dry run your second line of code to understand why your answer comes the way it does, but to answer your question in concise:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4;
}
I am trying to use a timer to achieve a sort of old animation used in the past to show that a process is running.
The way I would like to do that is by adding dots to a sentence (in a label control), for example:
"Process is running." to "Process is running.." and "Process is running..." with a limit of 3 dots and then revert back to a single dot.
I am not sure as to the fact using a timer here would be the best choice, but I thought it should work fine for such a simple example.
The code I used is as follows:
public string InitialProcessText;
private void StartBtn_Click(object sender, EventArgs e)
{
if(fileName != "No file selected")
{
ValidationLbl.Text = null;
ProcessLbl.Text = "Application is now running.";
//InitialProcessText = ProcessLbl.Text;
ProcessTimer.Start();
}
else
{
ValidationLbl.Text = "No file was added";
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
ProcessTimer.Stop();
}
private void ProcessTimer_Tick(object sender, EventArgs e)
{
_ticks++;
//For every two ticks, ProcessLbl.Text = InitialProcessText
ProcessLbl.Text += ".";
}
What could I add to set a limit of adding 2 dots and then remove the dots and add dots again (I would assume to do this in the ProcessTimer_Tick method)?
You can just use your _ticks variable:
private readonly int _ticksPerUpdate = 2;
private readonly int _maxNumberOfDots = 3;
private void ProcessTimer_Tick(object sender, EventArgs e)
{
_ticks++;
if(_ticks == (_ticksPerUpdate * (_maxNumberOfDots + 1)))
{
_ticks = 0;
ProcessLbl.Text = InitialProcessText;
}
else if(_ticks % _ticksPerUpdate == 0)
{
ProcessLbl.Text += ".";
}
}
Remember to reset the ticks counter every time you start the timer:
private void StartBtn_Click(object sender, EventArgs e)
{
if(fileName != "No file selected")
{
ValidationLbl.Text = null;
ProcessLbl.Text = "Application is now running.";
InitialProcessText = ProcessLbl.Text;
// reset the variable
_ticks = 0
ProcessTimer.Start();
}
else
{
ValidationLbl.Text = "No file was added";
}
}
I assume that _ticks counts the number of ticks. You could then go :
if(ticks%3 == 0)
{
ProcessLbl.Text = "Application is now running."
}
else
{
ProcessLbl.Text+=".";
}
Then, at 1st tick, 1%3=1 so it adds a dot, at 2nd tick, 2%3=2 so it adds a dot and 3rd tick, 3%3=0, so it gets back to original.
Just because...here's another approach:
private void ProcessTimer_Tick(object sender, EventArgs e)
{
ProcessLbl.Text = ProcessLbl.Text.EndsWith("...") ? ProcessLbl.Text.TrimEnd(".".ToCharArray()) + "." : ProcessLbl.Text + ".";
}
I tried to debug this and i cant figure out whats wrong with it.
Im trying to build a calculator but i keep getting this error.
double currentResult = 0;
int stringLengthStarter = 0;
int stringLengthCounter = 0;
public Form1()
{
InitializeComponent();
}
// Appends the numbers to the text box when the buttons are clicked
private void button1_Click(object sender, EventArgs e) // Click on the digit 1
{
if (clearingTextBoxFlag)
{
textBox1.Clear();
}
stringLengthCounter++;
textBox1.AppendText("1");
clearingTextBoxFlag = false;
}
private void plusButton_Click(object sender, EventArgs e) // Plus button clicked
{
pick = 1; // 1 - Plus operation
currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter));
stringLengthStarter = stringLengthCounter + 1;
stringLengthCounter = 0;
textBox1.AppendText("+");
}
private void equalsButton_MouseClick(object sender, MouseEventArgs e) // Mouse click on the equals button
{
textBox1.Clear();
if (pick == 1) // Plus operation
{
checkTextBox.Text = textBox1.Text;
currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter)); // The problem
textBox1.Text = "" + currentResult;
}
I'm trying to do 1+1= and it gets the execption at this line: currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter)); // The problem
In your equalsButton_MouseClick method, the first thing you do is to clear the textBox1, which will set the textBox1.Text to string.Empty. After that you try to make a substring of textBox1.Text, but the length of the string is 0, which is why your method is crashing. It's trying to access an index of the string that doesn't exist anymore.
Try moving the textBox1.Clear at the end of your method.
This question already has answers here:
How to approach: Write a Windows application that accepts any number of positive values [closed]
(2 answers)
Closed 10 years ago.
This is the assignment:
Task 1- Write a Windows application that accepts any number of positive values, that is inputted by a button. The user clicks another button to process all the inputted data at any time. The resulting output should be:
first output - sum of all the n entered numbers,
second output - on a listview show two columns with the following information-
column1 - the inputted numbers,
column2 - the percentages contributed by each number to the sum.
So far I have this:
{
InitializeComponent();
}
double number = 0, total = 0, numDisplay;
string[] numbers;
private void button1_Click(object sender, EventArgs e)
{
{
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
number = double.Parse(textBox1.Text);
if (number > 0)
{
total += number;
textBox1.Text = number.ToString();
numDisplay = double.Parse(textBox1.Text);
textBox1.Clear();
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar)) { }
else if (e.KeyChar == '.' && textBox1.Text.IndexOf(".") == -1) { }
else
{
e.Handled = true;
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
label1.Text = "sum: " + total.ToString();
}
}
Basically, the only thing I need to finish is making the 2 last columns.. soo..
Taking into account that I am totally new to this program...
How can I take numbers that are inputted into a textbox and store them, but show them on a listview when you press the button? I would like to store whatever amount... meaning the list would be looped.
So for example if I placed 1,2,3,4,5 as my inputs, I want it to show in my first column in my list view as 1-5 going down my first column and for my secound column I would like the percentages of the numbers to the sum so in this case of 1-5,
1/15
(1+2+3+4+5=15),
2/15,
3/15,
4/15,
5/15
all times by 100
UPDATE:
The question is not very clear. Thanks to Mr. #ChristofferLette, I realized, when or what if we want to enter a number like 15 21 12 24 and etc but the OP's TextBox had a function that to allow the number only.
This will be the solution and suggestion, The function of TextBox should we allow the , and backspace and all numbers, the hints is, we need to separate the numbers, so we can get the two, three or four etc. digits number and apply the .RegEx Class.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != ',')
e.Handled = true;
}
Then,
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
var text = Regex.Split(textBox1.Text, #"\D+");
var t = text.Select(c => decimal.Parse(c)).Sum(); //<--Get all the total
foreach (var i in text)
{
ListViewItem item = new ListViewItem();
item.Text = i;
item.SubItems.Add(((decimal.Parse(i) / t) * 100).ToString());
listView1.Items.Add(item);
}
//decimal total = listView1.Items.Cast<ListViewItem>()
// .Select(c => decimal.Parse(c.SubItems[1].Text))
// .Sum();
//ListViewItem item2 = new ListViewItem();
//item2.Text = "Total:";
//item2.SubItems.Add(total.ToString("#,#0.00"));
//listView1.Items.Add(item2);
}