I have this windows application
1.- So, first when I Add a number it added to listbox1 but not to list 2. I need to be add ed to listo 2 to
2.- I need the numbers be added separately... For example if I add number 202, it split on 2 after 0 after 2
3.- I need add button for FIFO, but I don't know how can I program it.
4.-Finally compare one by one it with listbox1 with listbox2 with polindrome method, and if its palindrome show message box, say "they are polindrome", if not, say "number it's not palindrome.
private void button1_Click(object sender, EventArgs e)
{
int newvalue;
if (int.TryParse(textBox1.Text, out newvalue))
{
numeros.Add(newvalue);
listBox1.Items.Add(textBox1.Text);
}
else
MessageBox.Show("insert a number");
textBox1.Clear();
textBox1.Focus();
}
For dealing with this problem you should keep your main data in memory (List<int>) and manipulate them using different methods and show the result in the listboxes.
Separating your digits can be done this way :
List<int> SeparateDigits(int n)
{
var result = new List<int>();
while(n>0)
{
result.Add(n % 10);
n /= 10;
}
return result;
}
After calling this method you can add the list data to both your listboxes if it's what you want.
(sorry for being late)
Good luck.
Related
I have a list of player numbers(int list), I also have a number of laps (int laps). I have to enter the number of the player into a text box each time the player completes a lap. If valid, the player number entered into the text box will be sent to a list. However, each player number cannot be entered more than the number of laps.
I'm new to windows forms so I've only used lists to solve the problem, I've seen people use dictionary to solve similar issues but I'm not quite sure how to incorporate that to solve this issue.
private void textBox2_TextChanged(object sender, EventArgs e)
{
bool result;
int RunnerNumberInOrder;
repeat2 = (getLaps2 * rows2);
textBox2.Focus();
//ReadPlayerNumber is the list that contains the list of the runners in the race.
//PlayerNumberInOrder int list is a global list and it is the list that the runners number order gets sent to if valid
result = int.TryParse(textBox2.Text, out RunnerNumberInOrder); //checks if the value entered is an integer
if (result == false || !ReadRunnerNumbers2.Contains(RunnerNumberInOrder)) //if the value entered is not an integer an error message will pop up and ask to enter a valid number
{
label3.Text = "Please enter a valid player number from the list";
}
else
{
if (RunnerOrder.Contains(RunnerNumberInOrder))
{
count++;
}
if (count == getLaps2)
{
count = 0;
label3.Text = "max laps for this runner has been entered";
invalid.Add(RunnerNumberInOrder); //invalid is an int list that I used to send the numbers of the runners that have completed all laps.
textBox2.Clear();
return;
}
}
if (invalid.Contains(RunnerNumberInOrder))
{
MessageBox.Show("Max number of laps for this runner has been entered");
textBox2.Clear();
}
if (result == true && ReadRunnerNumbers2.Contains(RunnerNumberInOrder) && !invalid.Contains(RunnerNumberInOrder))
{
RunnerOrder.Add(RunnerNumberInOrder); //if number entered is valid, the it is added to the global variable
PlayerNumbersEntered++;
label8.Text = RunnerNumberInOrder.ToString();//counts how many valid car numbers have been enterted
textBox2.Clear();
}
}
The code I have kinda works but it sometimes only allows one number 2 times when the number of laps is 3 and sometimes will allow more than the laps entered. I want an error message to pop up when the player's number equals to the number of laps and the number shouldn't be allowed any further. I also have to use a text_change. Cheers for the help in advance.
The main issue I see in your code I believe is the count variable which appears to be a global variable but you seems to use it like is count for specific RunnerNumbers.
The way I see it you could solve this by either creating a class of Runners that would have a number ID and the Count or, even simpler, to just get the count of that runner on the go as follows:
specificRunnerCount = RunnerOrder.Where(x => x == RunnerNumberInOrder).Count()
With this you could modify your code to something like this:
int specificRunnerCount = RunnerOrder.Where(x => x == RunnerNumberInOrder).Count();
if ((specificRunnerCount + 1) == getLaps2) // +1 because we haven't added this number to the count yet.
{
label3.Text = "max laps for this runner has been entered";
invalid.Add(RunnerNumberInOrder);
textBox2.Clear();
return;
}
// Continue code as is
Also, from your code, the part of code where you add a value to the invalid list: invalid.Add(RunnerNumberInOrder);, you use a return statement which ends the function. Due to this I don't see the need for you to check if the invalid list contains the runner number in if (invalid.Contains(RunnerNumberInOrder))
Hope this helps you.
I'm working on something for school, just a basic score calculator. I know it's not the prettiest code, but it works and that's more what the class is focused on here at the beginning.
The only issue that I have is that whenever I click "Display" it prints out 20 0s. 20 is the length of the array. Everything else is working. It adds the number I input into the array and replaces the 0s. But I don't want it to have 0s at all unless I specifically type them in.
Any help is appreciated.
Full code:
// Creates the list that displays the score
List<string> scoreList = new List<string>();
// Array to store up to 20 scores
int[] scoreArray = new int[20];
// class level variable to store current open slot in the array
int openSlot = 0;
public Form1()
{
InitializeComponent();
}
// Initializes variables that hold our math total and count of numbers entered
int total = 0;
int count = 0;
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void btnAdd_Click(object sender, System.EventArgs e)
{
if (openSlot <= scoreArray.GetUpperBound(0))
{
try
{
// Basic math for conversion of entered number and calculating total numbers entered
// and the averages of those numbers
int score = Convert.ToInt32(txtScore.Text);
total += score;
count += 1;
int average = total / count;
txtScoreTotal.Text = total.ToString();
txtScoreCount.Text = count.ToString();
txtAverage.Text = average.ToString();
txtScore.Focus();
}
catch(System.FormatException) // Makes sure that the user enters valid character into box
{
MessageBox.Show("Please enter valid number into box");
return;
}
// Adds the most recent entered number to the Score List
scoreList.Add(txtScore.Text);
}
// if statement to make sure that there is still room in the array to store the
// new entry
if (openSlot > scoreArray.GetUpperBound(0)) // GetUpperBound(0) returns the index of the last element in the first dimension
{
MessageBox.Show("The array is full! The most recent number was not added.");
txtScore.SelectAll();
txtScore.Focus();
return;
}
// Assigns a variable as an integer from the score text box
// to allow us to numerically sort the numbers in the scoreArray
int scoreParse = Int32.Parse(txtScore.Text);
// move the most recent number to the current open slot in the score array
scoreArray[openSlot] = scoreParse;
// add 1 to openSlot
openSlot += 1;
}
private void btnClear_Click(object sender, EventArgs e)
{
// Clears all input fields and resets variables to 0
openSlot = 0;
total = 0;
count = 0;
txtScore.Text = "";
txtScoreTotal.Text = "";
txtScoreCount.Text = "";
txtAverage.Text = "";
txtScore.Focus();
// Clears the array and list
int[] clearScoreArray = new int[20];
scoreArray = clearScoreArray;
List<string> clearScoreList = new List<string>();
scoreList = clearScoreList;
}
private void btnDisplay_Click(object sender, EventArgs e)
{
// If array has no stored values, display a MessageBox that informs user
if (scoreArray == null || scoreArray.Length == 0)
{
MessageBox.Show("There are no numbers to display");
return;
}
//move focus to the code textbox
txtScore.Focus();
// Creates a blank string variable named scr to input the scores into
// for the MessageBox
string scr = "";
foreach (var scoreAdded in scoreArray)
{
// Adds variable scr as the string to display
scr += scoreAdded + "\n";
}
// Sorts the array from lowest to highest number
Array.Sort(scoreArray);
// Displays a message box with the scores that were added
MessageBox.Show(scr);
}
}
When you declare a set amount of arrays (In your place it's 20), they get some sort of value, normally it's 0. Keep this is mind when you are using myArrayHere.length, cause it will check how many arrays have been declared (int[] array) and initialized (... = new array[]), not how many have been modified (given a value).
Best solution, IMO is creating a function, that would know how many elements in an array you will need or how many of them you are using (just have a function, that returns the amount of used variables, by checking it with a loop, and then modifying it later on... but that is one way to fix this issue, and there are better fixes than these I pointed out, but as I see you are newer to C# (prob.) fixing your issues with ok'ish code is good, as your first project should be meant for learning, later on, you can improve it and heck, if you are looking to become a pro, take some Programming courses on how to improve your code in general).
Good luck!
-Normantas
You can use nullable if you dont want zero as default value.
int? [] array = new int?[20] ;
Welcome to SO!
When an object is initially declared there is a default initialization value. In this case, 0 is the default value for an int in C#. The default value can often be changed at the initialization of the object if there's a supporting constructor.
When the int[] scoreArray = new int[20]; is declared, all 20 variables are assigned the value of 0. This is because C# does not allow uninitialized variables.
This link shows all default initialization values for C#.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table
I am using DataGridView in C# being civil engineer.
I want the values from a particular row. If the same value appears in a row, I want to display a message. For example, if 1 appears multiple time in a row, i want to display a message on every 1.
Here is how I am doing it:
private void button4_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView2.ColumnCount - 1; i++)
{
if (CategoryCLO[i] == 1)
{
MessageBox.Show("Here i am");
}
else
{
MessageBox.Show("I am not");
}
}
}
private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == 1)
{
CategoryCLO.Add(int.Parse(
dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()));
}
}
Problem:
It works right only one time. If a user replaces a value in a cell in DataGridView, it adds up another value corresponding to the newly added index of list.
Explanation:
The problem is that when user changes value in DataGridView, it got adds up in the list, thus increase the index of list , I want that index of list should be fix to the column index. and any change in particular cell , should change in that particular index rather than adding up.
Question:
I want that value should be placed in the previous index rather than creating new. In short, I want the indexes of list should be fixed to column number. How can I do it? any direction?
Note: Column numbers are variable depending upon the user
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.
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
}
}