Windows Form Application - C# Getting User Input - c#

I'm using C# to make a Windows Form Application. I have a form with 4 labels, 4 textboxes, and 3 buttons. The only textbox that can have anything entered inside of it is the 1 first box, the rest have TapStop = false. I want the user to be able to enter a bunch of numbers in that 1st textbox and I want those numbers to get added to get the average and total. I already have a button that the user can push once they enter something. What I'm trying to do it similar to a calculator. User enters 1 number, then another, then another so on. I want to take all of those numbers and get the total, the amount of numbers they entered, and the average. I'm having trouble getting all of those numbers ready to be calculated. I created an event handler for the Add button and declared variables for the average and total. I'm having trouble with these 2 things:
1- I'm not sure how to get the input every time the user enters something.
2- I'm not sure how to convert the numbers the user enters since default is string in text boxes.
Tried to be as specific as I could since I don't have any code besides the event handler I made and the variables I declared because I'm not sure what to do next.
Any suggestions for these 2 things? Thanks.

1- I'm not sure how to get the input every time the user enters something.
If you want to update your values based on user input without pushing the button you can use the TextChanged event, where to find it? just double click on the textbox in the designer, then everytime the user change the text in this textbox this event will fire.
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
2- I'm not sure how to convert the numbers the user enters since default is string in text boxes.
int value = Convert.ToInt32(textBox1.Text);
EDIT
so based on your comment, here is my solution.
//The entered values will be stored as List of integars.
List<int> enteredValues = new List<int>();
//The button will store each value in the List of integers.
private void button1_Click(object sender, EventArgs e)
{
int value;
if(int.TryParse(textBox1.Text,out value))
{
enteredValues.Add(value);
}
else
{
//Show error message here.
}
}
//This button will calculate the sum of entered values.
private void button2_Click(object sender, EventArgs e)
{
int totalValues = 0;
foreach(int val in enteredValues)
{
totalValues += val;
}
}

Related

Count the number of clicks for two different buttons with one calculate function

I'm sure this is simple but I can't seem to wrap my mind around it
I have two buttons in my C# wpf form: one to mark an answer right, one to mark it wrong. All I need to do is keep track of how many times each button is clicked, but with ONE calculate method.
Any ideas?
Use this
private int correctCounter = 0; // Declared at class level
private int incorrectCounter = 0; // Declared at class level
private void buttonsClicked(object sender, EventArgs e)
{
string s = (sender as Button).Text; // Or ((Button)sender).Text;
if(s == "Correct") { // Change "Correct" to whatever the text of the button is
correctCounter += 1;
} else if (s == "Incorrect") {
incorrectCounter += 1;
}
// Do other things
}
string s = (sender as Button).Text; Will get the text of the button that was clicked and then you just have to compare whatever text is in your two buttons.
More in depth:
(sender as Button) essentially casts the value of the sender to be a Button. So you will end up getting properties of the Button that called the method. You can also write it as ((Button)sender).Text
In your case, we can use the .Text value of the Button object to capture the text of the button. We can then compare the text of the buttons to see which one was clicked.
Having not worked with WPF itself, I'm not certain that this would work but if you had a public function and a pair of global integer variables, each button could call the public function with a boolean passed as a parameter and have the function increment the two variables.

How to set TextBox to only accept numbers?

I have already checked other questions here but the answers are not related to my issue. the following code allows textbox1 to only accept numbers if the physical keyboard (laptop) is pressed:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if ( !char.IsDigit(ch))
{
e.Handled = true;
}
}
but this is not what I wanted (I dont use physical laptop keyboard).
As shown in screenshot, I have windows form with buttons and a textbox. I designed this keyboard and it works well but I want textbox1 to only accept numbers and the ".".
There are only two lines of code inside each button (and only code in the project) which is:
private void buttonName_Click(object sender, EventArgs e)
{
// each button only has this code.
textBox1.Focus();
SendKeys.Send(buttonName.Text);
}
I know how to set txtbox to accept numbers if the physical (laptop ) keys are pressed but here in this case I have control buttons in windwos form and I want to set textBox1 to only accept numbers and the ".". Please help in how to achieve this. Thank you
Declare a string variable at form level, use it to store the last valid text and to restore it when an invalid text is entered on the TextChanged event of your textbox.
string previousText;
public Form1()
{
InitializeComponent();
previousText = String.Empty;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
int dummy, changeLenght, position;
if (!String.IsNullOrWhiteSpace(textBox1.Text) && !int.TryParse(textBox1.Text, out dummy))
{
position = textBox1.SelectionStart;
changeLenght = textBox1.TextLength - previousText.Length;
textBox1.Text = previousText;
textBox1.SelectionStart = position - changeLenght;
}
else
{
previousText = textBox1.Text;
}
}
position and changeLenght are used to keep the cursor where it was before restoring the text.
In case you want to accept numbers with decimals or something bigger than 2147483647, just change dummy to double and use double.TryParse instead of int.TryParse.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int changeLenght, position;
double dummy;
if (!String.IsNullOrWhiteSpace(textBox1.Text) && !double.TryParse(textBox1.Text, out dummy))
{
...
}
}
Suppose button1 is your button control, you could do this:
private void allButtons_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
char c = btn.Text[0]; //assuming all buttons have exactly 1 character
if(Char.IsDigit(c) || c == '.')
{
//process
textBox1.Focus();
SendKeys.Send(btn.Text);
}
//otherwise don't
}
I'm assuming you put this in a common handler, to which you already wired all your buttons (i.e. allButtons_Click).
Problem with this approach, it allows you to type values like 0.0.1, which are most likely invalid in your context. Another way to handle this is to process TextChanged event, store previous value, and if new value is invalid, restore the old one. Unfortunately, TextBox class does not have TextChanging event, which could be a cleaner option.
The benefit of you determining the invalid value is modularity. For example, if you later decide your user can enter any value, but only numbers can pass validation, you could move your check from TextChanged to Validate button click or similar.
Why users may want that - suppose one of the options for input is copy/paste - they want to paste invalid data and edit it to become valid, for example abc123.5. If you limit them at the entry, this value will not be there at all, so they now need to manually paste into Notepad, cut out in the invalid characters, and paste again, which goes against productivity.
Generally, before implementing any user interface limitation, read "I won't allow my user to...", think well, whether it's justified enough. More often than not, you don't need to limit the user, even for the good purpose of keeping your DB valid etc. If possible, never put a concrete wall in front of them, you just need to guide them correctly through your workflow. You want users on your side, not against you.

in c# i want to pass a variable from one button1 to other button2

I was trying to add 2 numbers by using a single text box (both the input and output must be specified in a single textbox).when I click on '+' button the data on the textbox1 should arise and and should enable the user to type a new number, those 2 numbers should be added and should be displayed when an '=' button is clicked
so my problem is:
if suppose if a button1 is clicked then a variable stored the value of that button1 and only displays that value when button2 is clicked
please help me in finding out
If you have a value in a text field, when button 1 is clicked, the value from the text field must be extracted from the text field and saved somewhere. This is done in the click event handler for the button.
Depending on what type of a program you are working in, the place you save the info may be different. You may save this in a temporary variable, a database, the session, hidden field, or somewhere else, it just needs to be saved.
When button 2 is clicked, extract the value in the same way and save it somewhere. If you have two values in the designated saved locations when you click the '=' button, use these values, add them together, and populate the text box with the result.
You need just a variable to store first number.Define it in the class level:
int firstNumber;
Then when you get your number from textBox1 store it in the firstNumber,for example in button one (+) click:
int temp;
if(int.TryParse(textBox1.Text, out temp)
{
firtNumber = temp;
textBox1.Clear(); // or set visible or enabled to false
}
In (=) button:
int temp;
if(int.TryParse(textBox2.Text, out temp)
{
label1.Text = String.Format("Result of {0} + {1} is : {2}",firstNumber, temp, firstnumber+temp);
}
Ok, so one textbox that the user inputs a value into. One they use the + button the number disappears and they are able to put a second number in the textbox. The problem is you wish to store the value in the textbox prior to clearing it. This is easy, and should be handled in the Event Handler for the + button_click.
private int value1;
private int value2;
private int total;
private void addButton_Click(object sender, EventArgs e)
{
int.TryParse(textbox1.Text, out value1);
}
private void equalButton_Click(object sender, EventArgs e)
{
int.TryParse(textbox1.Text, out value2);
total = value1 + value2;
textbox1.Text = total.ToString();
}

How to send the value to textbox programatically?

I have one textbox and to that textbox i have to send value from virtual keyboard i desigend.
I am send like
txtNumber.Text = txtNumber.Text.Insert(txtNumber.CaretIndex, ((Button)sender).Content.ToString());
txtNumber.CaretIndex += txtNumber.Text.Length;
txtNumber.focus();
The problem is when user forcefully place the cursor in between the text after typing some character, then pressing the key means first time the value is inserting correctly and after that cursor needs to be there.
This logic above make it to stay the cursor position in the end.
How to achieve this ?
Use this code, i have checked it:
int CurrentIndex;
private void textNumber_Click(object sender, EventArgs e)
{
CurrentIndex = textNumber.SelectionStart;
}
private void Key_Click(object sender, EventArgs e)
{
textNumber.Text = textNumber.Text.Insert(CurrentIndex, "_");
}
If I'm understanding the question, I would keep the string being modified in a buffer string variable and make your changes there depending on the virtual kb input. Once this is done, update the TextBox value by txtNumber.Text = bufferedString;
try to do like this txtNumber.Text +=// your code..
and try to put txtNumber.focus(); this line at the start.
There are a couple to ways you can do this.
When the user intents that he/she wants to use the virtual keyboard,
by click of a checkbox or something, you can make the textbox readonly.
or you could set the CaretIndex in the lost focus event of the textbox.
else you can simply call the AppendText("nextsetofchars") method
http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.appendtext.aspx
You can also set the SelectionStart to the length of the string in the lost focus event.
http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.selectionstart.aspx

Passing Value From Form to Textbox

The title is a little vague. I have a form with several textboxes that require user input. The input is all numerical. This is a touchscreen application, so when the textbox gets focus, a "numberpad" form is displayed for the user to input the number. The user's input is displayed on the "numberpad" form.
The question: How do I get that input to be set as the text property of the calling textbox?
I know I could pass some int value then use a big switch statement when the value is to be passed, but there are around 30 textboxes. Any ideas?
In your NumberPad form, have a property that is your result:
public int Result { get; private set; }
When the user hits the button to save the data, assign the value and set the DialogResult for the form:
private void btnSave_Click(object sender, EventArgs e)
{
Result = // whatever
DialogResult = DialogResult.OK;
}
In the calling form, check the result and only process if it is OK (in other words, the NumberPad was saved and not cancelled):
NumberPad pad = new NumberPad();
if (pad.ShowDialog() == DialogResult.OK)
{
txtBox.Text = pad.Result.ToString();
}

Categories