Hi I am new to programming
I have a masked textbox into which a user inputs an account number, then I have a label which displays the number of users or rather display the number of times the account number has been changed. I.e. as each account number is being entered the customer count should increase.
I don't have an example code because I do not even know where to start
Please show me how to code this, I am using a form in Visual Studio
have it add the input to a list or array, and then you can run a check to see if the array/list contains that input already. If so, do not add the input again, if it does not, then add the input. You can then tell how many customers you have by the size of the list.
If you are taking in the users input as a string do a String Comparison or if you're doing strictly a numerical account number and am taking it in as an int then simply see if the numbers are different
For strings use:
result = input1.Equals(input2, StringComparison.OrdinalIgnoreCase);
For ints just use an If statement to test:
if(input1 != input2) {
Console.WriteLine("Input has changed")
else
Console.WriteLine("Input has not changed");
}
I'm guessing the user has to push a button after the user has entered the password? If so, we can easily track this. First we make a global int variable like so: private int userCount = 0;
Then we add an event to our button:
private void btnAccountNumber_Click(object sender, EventArgs e)
{
userCount = userCount + 1;
displayLabel.Text = userCount.ToString() + " Customers";
maskedTextBox.Clear();
}
So in this button we add our customer that just clicked on our button to the total of users.
Next we show that number in the label you created. And finally we clear the maskedTextBox of userInput so the next customer can use it.
Related
I am creating this simple block of code that asks the user to fill an array, and then it asks the user to enter in the subscript value to print what value is in that position. What would I do to create a loop that asks the user what index element I am wanting to see and it prints what element is at the index position? For example I have this array of [1, 2, 3] and I enter in 0 it would return me the value 1. I hope you have the idea now.
Here's the code:
using System;
namespace Chapter_11
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[3]; // array initialization
for (int i = 1; i < 5; i++) // user input values
{
Console.Write("Enter in value {0}: ", i);
Console.ReadLine();
}
Console.Write("\n");
while (true)
{
Console.Write("Enter in a subscript value between 0 - 3 or 999 to quit: ");
string exit = Console.ReadLine();
if (exit == "999") // check string
{
break;
}
}
}
}
}
As I even see from your namespace, this looks like some sort of homework or maybe class lab work. You will really need to understand what is happening and why is happening otherwise every time, you will have to find someone to write the code for you.
(I would love to write this in comments section as it is not exactly an answer, but it would not fit there, and I feel this is even better for you than a ready answer)
I copied your code to console app and it is working. So that is good.
Let's look at closer what you are trying to do.
It seems everything is working as expected and if user press "999" it exits the code. So you are almost there. Check out the arrays from this link as it is a nice summary of what are arrays and how they work.
if (exit == "999") // check string
at this line, you are storing user entry to exit variable, as I would suggest to rename your variable to userInput as it will be more meaningful because it will not be only "exit", it will be holding the value of user entry.
So you basically grab the input from the user.
There are ways of checking conditions in C# and if-else statements are one of them.
You already check as if (exit == "999") if user entered "exit" code. What you can do is (And as a pseudo code )
Get user's entry // you already do that
Check if user wants to exit (you already do that with if (exit ==
"999") ) If not, than you can use Else statement which will
check if your If condition does not
satisfy as true.
Then in the else statement, whatever user entered, you can use it as an index of your array. (check Array index from here)
Again this code is not the best way to do it, but should get you going.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I got 4 textboxes that I want to put values in, and I want it to find the average number from the values of the inputted values to the 4(or more) textboxes.
I want the average to display in a readonly box (is richtextbox good for this?).
You can use both a RichTextBox and normal TextBox for this. To ensure that it is read-only, in the designer page do the following;
Select the TextBox > Scroll under properties window > Behavior Section > Read-Only property
Setting this property to true will make the TextBox non-editable by the user.
After you have the 4 editable TextBoxes and 1 non-editable, you can implement something like the following to add up the numeric values of TextBoxes and display it in the readonly TextBox.
private void AverageAndDisplay()
{
try
{
//Convert values to numeric
decimal one = Convert.ToDecimal(textBox1.Text);
decimal two = Convert.ToDecimal(textBox2.Text);
decimal three = Convert.ToDecimal(textBox3.Text);
decimal four = Convert.ToDecimal(textBox4.Text);
//Find the average
decimal average = (one + two + three + four) / 4.0m;
//Show the average, after formatting the number as a two decimal string representation
textBox5.Text = string.Format("{0:0.00}", average);
}
catch(Exception e) //Converting to a number from a string can causes errors
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
So you should have this steps:
Create 4 textboxes. Let's this buttons has ID Value1Txt, Value2Txt, Value3Txt, Value4Txt
Add button with text Calculate Average Value. The ID of the button should be CalculateAverageBtn
Add the Label in which you will show the Average. The ID of this Label should be AverageValueLbl
Attach OnClick event on the CalculateAverageBtn. You could do it using the signature of the button OnClick="CalculateAverageBtn_Click" or doing it in the code
//this should be inside InitializeComponents method
CalculateAverageBtn.OnClick += CalculateAverageBtn_Click;
protected void CalculateAverageBtn_Click(object sender, EventArgs e)
{
//...code
}
Now in the body of CalculateAverageBtn_Click you should Parse the values of the TextBoxes and calculate the average. You could do this using decimal.TryParse method
decimal value1 = 0;
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
//if you come in this if the parsing of the value is not successful so
you need to show error message to the user. This happen when the user
enters text like 123Test, this is not a number. So you need to show
error message
}
Create a label in which you will show the error message. Let's call it ErrorLbl. So when the parsing is not successful we will write in this label the error message.
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
ErrorLbl.Text = "The value of value 1 textbox is not valid number"
return; //exit the button click method
}
Calculate the average of 4 textboxes and write it in the AverageValueLbl. This should be in button event click
AverageValueLbl.Text = (value1+value2+value3+valu4)/4.ToString();
Try to understand what you are doing, don't copy/paste mindlessly code. This is pretty much beginner programming. For sure this is homework, so try to understand it because in the future harder homeworks you will be lost.
I am working a small sale invoice application on WF. I have a customer table and a product table. Then, I populate customer name and product name via comboboxes on Sale-form. Once user selects an item from ProductName combobox, other textboxes like Price and ProductID are auto-populated with data from Product Table from database. I have also a textbox named txtQuantity that can be entered for Quantity for product order. Once a number is entered for Quantity, subtotal, GST(which is Tax in Singapore), and total are auto-calculated and those values appear on textboxes of Subtotal, GST and Total. When a user delete quantity to update/change, it shows error as "Format Exception was unhanded, input string was not in a correct format". I like to prevent this error to stop working my application when user delete quantity or want to change to a new value. How do I go about it because I am complete lost here. Below is my code.
private void txtQuantity_TextChanged(object sender, EventArgs e)
{
int iQuantity = Convert.ToInt32(txtQuantity.Text);
decimal dPrice = Convert.ToDecimal(txtPrice.Text);
decimal dSubtotal = dPrice * iQuantity;
decimal dGST = dSubtotal * 7/100;
decimal dTotal = dSubtotal + dGST;
txtSubTotal.Text = Convert.ToString(dSubtotal);
txtGST.Text = Convert.ToString(dGST);
txtTotal.Text = Convert.ToString(dTotal);
}
I also wanted to set parameters for quantity textbox as only for entering numbers. I will do that later. This is going to be another thing to explore. Any advice for this is also welcomed and appreciated.
I would run all of your string inputs through the following (or something similar) before trying to assign them to an integer variable, especially when dealing with direct user input.
string myVar1;
//Something that assigns a value to myVar1
if(String.IsNullOrEmpty(myVar1))
{
myVar1 = "0";
}
else
{
int number;
bool result = Int32.TryParse(myVar1, out number);
if (result)
{
//you have a valid input and valid parse, do whatever you need with number variable
}
else
{
//bad input, reset to blank and show error message
}
}
Note the above code is an example and while fairly close to what you probably want, you will need to modify it before just copy/pasting it into your application
I have a program that generates a control number. Control number contains 13 numbers. The first 3 numbers is generated if the user is a maritime education, it is 100, but if the user is a general education, it is 101, then the following 5 numbers is a random numbers. Then the last 5 digits is the ID number of the user.
Code :
Random rand = new Random();
int startingDigits;
if (CmbEducation.SelectedItem.Equals("Maritime Education"))
{
startingDigits = 100;
string IdNumber = TxtIDnum.Text;
string controlNumber = string.Format("{0}{1}{2}",
startingDigits, rand.Next(10000, 99999).ToString(), IdNumber);
TxtControlNum.Text = controlNumber;
}
else if (CmbEducation.SelectedItem.Equals("General Education"))
{
startingDigits = 101;
string IdNumber = TxtIDnum.Text;
string controlNumber = string.Format("{0}{1}{2}",
startingDigits, rand.Next(10000, 99999).ToString(), IdNumber);
TxtControlNum.Text = controlNumber;
}
My problem is, I want to make an if..else condition. but i want to read the first 3 numbers of the control number how do i do it? Thanks :)
edited :
I am using the control number in another form now for password. So i want to read the first 3 numbers to get if the user is a marine education or a general education.
Now, I am in another form, i just copied the text from the login page where the password is the control number to the textbox in another form. so how do i read first 3 numbers inside a textbox?
Not sure if I'm reading your question correctly, but if all you need is to read the first three digits, just do:
var start = new String(controlNumber.Take(3).ToArray());
or
var start = controlNumber.Substring(0,3);
It's not clear what you mean by "read inside a textbox". Do you want to read them from a textbox? Then try:
TextboxName.Text.Substring(0,3);
If you want to place them in a textbox, use:
TextboxName.Text = controlNumber.Substring(0,3);
Update: I'll give this one more try. This should be self-explanatory, assuming you've got start as above:
if (start.Equals("100"))
{
// Do something
}
else if (start.Equals("101"))
{
// Do something else
}
else
{
// ...take a nap?
}
var controlNumberPrefix = myTextBox.Text.Substring(0, 3);
switch (controlNumberPrefix)
{
case "100":/* Maritime education - do something */ ; break;
case "101":/* Gen education - do something */ ; break;
}
or
var controlNumberPrefix = myTextBox.Text.Substring(0, 3);
if(controlNumberPrefix == "100")
// Do something
else if (controlNumberPrefix =="101")
// Do something
Edit:
Its the same thing with textbox. Just use the Text property of the textbox.
I need to build a form that allows a user to enter 100 different measurements. Then enter 100 different weights. I want to use the same text boxes. One for the measurements, one for the weights. Then have them store the value and then reset to accept the next value and so on. Can anyone point me in the right direction to accomplish this? I have searched for over an hour and can't find anything. Thank you in advance for your help.
When user clicks submit button, add to list or dictionary your value of both textboxes. Do this until wanted number of list.Count is reached. Let me know if I didn't understand your question right.
In WPF (C#) it would look something like this.
// Dictionary to save values
Dictionary<string, int> dict = new Dictionary<string, int>();
// Method that is called on user submit button click
private void HandleSubmit(object sender, EventArgs args) {
// Add values of both textboxes to dictionary
dict.Add(textBox1.Text, Int32.Parse(textBox2.Text));
// Check if all data is entered
// then activate custom method
if(dict.Count >= 100) {
CUSTOMMETHOD(dict);
}
}
-- EDIT --
#briskovich As I understood your comment. You want to save all 100 pressure samples first and then enter 100 weight samples. In that case there is no need to use dictionary, you could use two List<int> for pressure and weight. In that case, code would look something like this:
// Variables to save our data
// numberValues - number of values user needs to enter
// pressureList - list of entered pressure data
// weightList - list of entered weight data
int numberValues = 100;
List<int> pressureList = new List<int>();
List<int> weightList = new List<int>();
// Method that is called on user submit button click
// This method uses only one text box to input data,
// first we input pressure data until limit is reached
// and then weight data
private void HandleSubmit(object sender, EventArgs args) {
// Check if we are still entering pressure data, that
// is until we reach numberValues of pressure data values
// Same thing goes for weight list
if (pressureList.Count < numberValues) {
pressureList.Add(Int32.Parse(textBox1.Text));
}
else if (weightList.Count < numberValues) {
weightList.Add(Int32.Parse(textBox1.Text));
}
else {
// When we have #numberValues of values in both
// lists we can call custom method to process data
CUSTOMMETHOD(pressureList, weightList);
}
}
// Method for processing data
private void CUSTOMMETHOD(List<int> pressures, List<int> weights) {
// This loop will go through all values collected and
// will give you access to both pressure and weight on
// each iteration
for (int index = 0; index < numberValues; index++) {
int currentPressure = pressures.ElementAt(index);
int currentWeight = weights.ElementAt(index);
// Do processing here
}
}