To get text from two textboxs and add the elements to an array - c#

I want to add the elements from the textboxes to the array but every time I try adding the names it throws an exception. I want to add the elements after the button is clicked.
private void Grade_Click(object sender, EventArgs e)
{
string name;
double grade;
nametextbox.Text = "";
gradetextbox.Text = "";
for (int i = 0; i < 10; i++)
{
grade = Convert.ToDouble(gradetextbox.Text);
grades[i] += grade;
name = nametextbox.Text;
names[i] += name;
}
}

You do this:
gradetextbox.Text = "";
Which sets the Text property to an empty string. Then you do this:
grade = Convert.ToDouble(gradetextbox.Text);
which is trying to convert the empty string to a double, which clearly does not work so it throws an exception.
What you probably need is this:
private double[] grades = new double[10]; // 10 grades
private string[] names = new string[10]; // 10 names
private int currentIndex = 0;
private void Grade_Click(object sender, EventArgs e)
{
if (currentIndex > 10)
{
MessageBox.Show("No more enteries allowed");
}
string name;
double grade;
if (double.TryParse(gradetextbox.Text, out grade))
{
grades[currentIndex] += grade;
}
else
{
MessageBox.Show("Grade enterd is not a valid grade");
return;// do nothing else
}
name = nametextbox.Text;
names[i] += name;
// now clear the textboxes so user can enter another value
nametextbox.Text = "";
gradetextbox.Text = "";
currentIndex = currentIndex + 1;
}

Related

how can i adding up numbers from an array using the foreach loop

i've made an array with numbers.
i want to ad up the numbers form the array and show the result in a textbox.
i've to use the foreach loop.
i've already searched on the internet but i can't find anything that helped me.
this is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnsortar_Click(object sender, EventArgs e)
{
//opdr 9
int[] getallen = { 4,5,9,8,31,44,76,63,88,59 };
int index = 1;
int lengteArray = getallen.Length;
tbsortar.Text = getallen[0].ToString();
while (index < lengteArray)
{
Array.Sort(getallen);
tbsortar.Text = tbsortar.Text + "," + getallen[index].ToString();
index++;
}
//opdr 10
string[] namen = { "kees", "jan", "piet", "henk" };
Array.Sort(namen);
int lengteArray1 = namen.Length;
tbopdr10.Text = namen[0];
for (int i=1; i<lengteArray1; i++)
{
string newLine = Environment.NewLine;
tbopdr10.Text = tbopdr10.Text +newLine + namen[i] ;
}
//opdr 11
double totaal = 0;
foreach(int getal in getallen)
{
//toaal van getallen is 392
totaal += getal;
tbopdr11.Text = tbopdr11.Text + totaal;
}
}
}
Try this:
int[] Numbers = { 1, 2, 3 };
int Result = 0;
for (int i = 0; i < Numbers.Length; i++)
{
Result += Numbers[i];
}
TextBox1.Text = System.Convert.ToString(Result);
The textbox's name is TextBox1.
can't you just use sum?
getallen.Sum()
https://dotnetfiddle.net/sTn1kp

Limit line length in multiline textbox

I need to limit the number of characters on a single line that a user can enter into a multiline textbox. I have a function that can do that for data typed in, but not for data cut and pasted in.
I've tried reading the textbox into an array, using substring, and copying back to the text string, but this code (posted) throws an exception.
private void LongLine_TextChanged(object sender, TextChangedEventArgs e)
{
int lineCount =
((System.Windows.Controls.TextBox)sender).LineCount;
//string newText = "";
for (int i = 0; i < lineCount; i++)
{
if
(((System.Windows.Controls.TextBox)sender).GetLineLength(i) > 20)
{
string textString = ((System.Windows.Controls.TextBox)sender).Text;
string[] textArray = Regex.Split(textString, "\r\n");
textString = "";
for (int k =0; k < textArray.Length; k++)
{
String textSubstring = textArray[k].Substring(0, 20);
textString += textSubstring;
}
((System.Windows.Controls.TextBox)sender).Text = textString;
}
}
e.Handled = true;
}
This does what you seem to be asking for:
It truncates the end of any line that is longer than 20 as you type and when you paste or otherwise change the text.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
const int MAX_LINE_LENGTH = 20;
var textbox = sender as TextBox;
var exceedsLength = false;
// First test if we need to modify the text
for (int i = 0; i < textbox.LineCount; i++)
{
if (textbox.GetLineLength(i) > MAX_LINE_LENGTH)
{
exceedsLength = true;
break;
}
}
if (exceedsLength)
{
// Split the text into lines
string[] oldTextArray = textbox.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var newTextLines = new List<string>(textbox.LineCount);
for (int k = 0; k < oldTextArray.Length; k++)
{
// truncate each line
newTextLines.Add(string.Concat(oldTextArray[k].Take(MAX_LINE_LENGTH)));
}
// Save the cursor position
var cursorPos = textbox.SelectionStart;
// To avoid the text change calling back into this event, detach the event while setting the Text property
textbox.TextChanged -= TextBox_TextChanged;
// Set the new text
textbox.Text = string.Join(Environment.NewLine, newTextLines);
textbox.TextChanged += TextBox_TextChanged;
// Restore the cursor position
textbox.SelectionStart = cursorPos;
// if at the end of the line, the position will advance automatically to the next line, supress that
if (textbox.SelectionStart != cursorPos)
{
textbox.SelectionStart = cursorPos - 1;
}
}
e.Handled = true;
}

Array doesn't display in the message box - C#

I'm trying to display 5 scores in an array, but unfortunately all I get in the message box for the results is 0.
Any help would be appreciated.
public partial class Form1 : Form
{
private int[] scoresArray = new int[5];
private int scoreTotal = 0;
private int scoreCount = 0;
public Form1()
{
InitializeComponent();
}
when the add button is clicked the scores are stored in the array up to 5 times.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (txtScore.Text == "")
{
MessageBox.Show("Score is required", "Entry Error");
}
else
{
int score = Convert.ToInt32(txtScore.Text);
decimal average = 0;
if (score >= 0 && score <= 100)
{
if (scoreCount != 4)
{
scoreTotal += score;
scoresArray[scoreCount] = score;
scoreCount++;
average = scoreTotal / scoreCount;
}
else
{
MessageBox.Show("Array is full");
}
txtScoreTotal.Text = scoreTotal.ToString();
txtScoreCount.Text = (scoreCount + 1).ToString();
txtAverage.Text = average.ToString();
}
else
{
MessageBox.Show("Score must be greater than 0 and less than or equal to 100.", "Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid number for the Score field.", "Entry Error");
}
txtScore.Focus();
}
private void btnDisplayScores_Click(object sender, EventArgs e)
{
string message = "";
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
MessageBox.Show(message, "Scores");
}
You keep overwriting message in this loop:
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
So it's only ever going to show the last value. You probably want to append to it instead:
for (int i = 0; i < scoresArray.Length; i++)
{
message += scoresArray[i].ToString() + "\n";
}

Printing an array in a GUI label in visual studio with C#

So I am trying to figure out how to print out a list of bowling names and scores in my program. It is way simple when using a console. I am trying to figure out how to print the array into a label on a GUI? Any suggestions? I tried if/else if statements but obviously it didn't work.
Here is my form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_9
{
public partial class Form1 : Form
{
//Declare a reference variable to the class
private BowlingTeam myBowlingTeam;
const int MAX = 20;
const int TWO = 2;
int size = 0;
int count = 0;
//Array to store the names and scores so they can be printed
string[] nameAndScoreArray = new string[MAX];
public Form1()
{
InitializeComponent();
myBowlingTeam = new BowlingTeam();//Create a BowlingTeam object with the default constructor
}
//ExitToolStripMenuItem1_Click
//Purpose: To close the application when clicked
//Parameters: The sending object and the event arguments
//Returns: nothing
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//Enter Button Clicked
//Purpose: To store the info in an array when the button is pressed
//Parameters: The sending object and the event arguments
//Returns: nothing
private void button1_Click(object sender, EventArgs e)
{
//Get info from the text box and store it in a variable
string aNameAndScore = nameTextBox.Text;
//Set the name and score
myBowlingTeam.SetNameAndScore(aNameAndScore);
//Get the information from the text box and store it in a variable
string nameAndScore = myBowlingTeam.GetNameAndScore();
if (nameAndScore != "")
{
string printName = "";
string printScore = "";
//Split the string into two separte pieces of data
myBowlingTeam.SplitAndDisperseArray();
//Print the name of the bowler in the score box
string name = myBowlingTeam.GetAName();
//Change the int into a string then
//print the score of the bowler in the score box
int score = myBowlingTeam.GetAScore();
string strScore = String.Format("{0:d}", score);
//Store the name and score in an array to use them to print out the
//names and scores later
if (size < MAX)
{
nameAndScoreArray[size] = name;
nameAndScoreArray[size + 1] = strScore;
printName = nameAndScoreArray[size];
printScore = nameAndScoreArray[size + 1];
}
string strNameAndScore = printName + " " + printScore;
if (scoreLabel.Text == "")
{
scoreLabel.Text = strNameAndScore;
}
else if(scoreLabelTwo.Text == "")
{
scoreLabelTwo.Text = strNameAndScore;
}
else if(scoreLabelThree.Text == "")
{
scoreLabelThree.Text = strNameAndScore;
}
else if(scoreLabelFour.Text == "")
{
scoreLabelFour.Text = strNameAndScore;
}
else if(scoreLabelFive.Text == "")
{
scoreLabelFive.Text = strNameAndScore;
}
else if(scoreLabelSix.Text == "")
{
scoreLabelSix.Text = strNameAndScore;
}
else if(scoreLabelSeven.Text == "")
{
scoreLabelSeven.Text = strNameAndScore;
}
else if(scoreLabelEight.Text == "")
{
scoreLabelEight.Text = strNameAndScore;
}
else if(scoreLabelNine.Text == "")
{
scoreLabelNine.Text = strNameAndScore;
}
else if(scoreLabelTen.Text == "")
{
scoreLabelTen.Text = strNameAndScore;
}
//Clear the text box
nameTextBox.Clear();
}
else//If there is nothing in the text box
{
//Calculate the highest score and get the bowler's name
int highestScore = myBowlingTeam.CalcHighestScore();
string highestName = myBowlingTeam.GetHighestBowlerName();
//Calaculate the lowest score and get the bowler's name
int lowestScore = myBowlingTeam.CalcLowestScore();
string lowestName = myBowlingTeam.GetLowestBowlerName();
//Calculate the avg acore
double avgScore = myBowlingTeam.CalcAvgScore();
//Convert the numbers into strings
string strHighScore = String.Format("{0:d}", highestScore);
string strLowScore = String.Format("{0:d}", lowestScore);
string strAvgScore = String.Format("{0:f2}", avgScore);
//Display the information in the appropriate labels
highScoreNameLabel.Text = highestName;
highScoreLabel.Text = strHighScore;
lowScoreNameLabel.Text = lowestName;
lowScoreLabel.Text = strLowScore;
avgScoreLabel.Text = strAvgScore;
}
}
//Print Scores Method
//Purpose: To print the names and scores
//Parameters: An Array
//Returns: Nothing
public void PrintNamesAndScores(ref string[] anArray)
{
for(int i = 0; i < size; i++)
{
Console.WriteLine("{0} {1:d}", anArray[i], anArray[i + 1]);
i++;
}
}
//Nothing
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
}
// nothing
private void nameTextBox_KeyDown(object sender, KeyEventArgs e)
{
}
//Nothing
private void scoreTextBox_KeyDown(object sender, KeyEventArgs e)
{
}
//Nothing
private void label10_Click(object sender, EventArgs e)
{
}
//nothing
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Here is my class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_9
{
class BowlingTeam
{
const int MAX = 10;
//local variables
int sizeOfName = 0;
int sizeOfScore = 0;
//Declare Private Data Members
private string nameAndScore = "";
private string name = "";
private int score = 0;
private string[] nameArray = new string[MAX];
private int[] scoreArray = new int[MAX];
private string[] nameAndScoreArray = new string[MAX];
//Default Constructor
//Purpose: To set the initial values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam()
{
nameAndScore = "";
name = "";
score = 0;
for(int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for(int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Parameterized Constructor
//Purpose: To set the values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam(string aString)
{
nameAndScore = aString;
name = "";
score = 0;
for (int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for (int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Split the Input Method
//Purpose: To Split up the data in the array
//Parameters: An array of strings
//Returns: Nothing
public void SplitAndDisperseArray()
{
nameAndScoreArray = nameAndScore.Split();
name = nameAndScoreArray[0];
score = int.Parse(nameAndScoreArray[1]);
//Place the name and the score in their one arrays
PlaceInNameArray(name);
PlaceInScoreArray(score);
}
//Find Highest Score Method
//Purpose: To find the highest score
//Parameters: An array of int
//Returns: An int
public int CalcHighestScore()
{
int highestScore = scoreArray[0];
for (int i = 1; i < sizeOfScore; i++ )
{
if (highestScore > scoreArray[i])
{
highestScore = highestScore;
}
else
{
highestScore = scoreArray[i];
}
}
return highestScore;
}
//Find Lowest Score Method
//Purpose: To find the lowest score
//Parameters: An array of int
//Returns: An int
public int CalcLowestScore()
{
int lowestScore = scoreArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (lowestScore < scoreArray[i])
{
lowestScore = lowestScore;
}
else
{
lowestScore = scoreArray[i];
}
}
return lowestScore;
}
//Calulate Avg. Score Method
//Purpose: To calculate the avg score
//Parameters: An array of int
//Returns: An double
public double CalcAvgScore()
{
int sum = 0;
double avg = sizeOfScore;
//Add up all of the elements in the array
for (int i = 0; i < sizeOfScore; i++)
{
sum += scoreArray[i];
}
//Divide the sum by the size of the array
return avg = sum / avg;
}
//Set Score Array Method
//Purpose: To put scores in the score array
//Parameters: An int
//Returns: Nothing
public void PlaceInScoreArray(int aScore)
{
scoreArray[sizeOfScore] = score;
sizeOfScore++;
}
//Set Name Array Method
//Purpose: To put names in the names array
//Parameters: A string
//Returns: Nothing
public void PlaceInNameArray(string aName)
{
nameArray[sizeOfName] = name;
sizeOfName++;
}
//Get Name and Score Method
//Purpose: To get the name and score
//Parameters: None
//Returns: A string
public string GetNameAndScore()
{
return nameAndScore;
}
//Set Name and Score Method
//Purpose: To set the name and score
//Parameters: A String
//Returns: None
public void SetNameAndScore(string aNameAndScore)
{
nameAndScore = aNameAndScore;
}
//Get Bowler Name Of Highest Score Method
//Purpose: To get the name of the bowler with the highest score
//Parameters: None
//Returns: A String
public string GetHighestBowlerName()
{
int highestScore = scoreArray[0];
string bowlersName = nameArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (highestScore > scoreArray[i])
{
highestScore = highestScore;
bowlersName = bowlersName;
}
else
{
highestScore = scoreArray[i];
bowlersName = nameArray[i];
}
}
return bowlersName;
}
//Get Bowler Name Of Lowest Score Method
//Purpose: To get the name of the bowler with the lowest score
//Parameters: None
//Returns: A String
public string GetLowestBowlerName()
{
int lowestScore = scoreArray[0];
string bowlersName = nameArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (lowestScore < scoreArray[i])
{
lowestScore = lowestScore;
bowlersName = bowlersName;
}
else
{
lowestScore = scoreArray[i];
bowlersName = nameArray[i];
}
}
return bowlersName;
}
//Print Bowler's Names
//Purpose: To print the names the bowlers
//Parameters: None
//Returns: A String
public string GetAName()
{
string name = "";
for (int i = 0; i < sizeOfName; i++)
{
name = nameArray[i];
}
return name;
}
//Print Bowler's Scores
//Purpose: To print the names the bowlers
//Parameters: None
//Returns: A String
public int GetAScore()
{
int score = 0;
for (int i = 0; i < sizeOfScore; i++)
{
score = scoreArray[i];
}
return score;
}
}
}
As a general solution, I'd suggest that using LINQ to output a list of one String per item and then using String.Join to join them into a single String is the most succinct option, e.g.
myLabel.Text = string.Join(Environment.NewLine, myArray.Select(obj => string.Format("{0}, {1}", obj.Property1, obj.Property2)));

select name from array, selected name print in listBox1 and remaining in listBox2

I am having this error:
Index was out of range. Must be non-negative and less than the size of the collection.
I spent a long time trying to solve it, but I could not. Please I need help
public partial class Form1 : Form
{
string[] generate = new string[] {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Name14","Name15","Name16","Name17","Name18","Name19","Name20" };
string[] n = new string[] { "Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10", "Name11", "Name12", "Name13", "Name14", "Name15", "Name16", "Name17", "Name18", "Name19", "Name20" };
String[] a = new String[20];
string name;
int Num;
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) // START btn
{
Num = int.Parse(textBox1.Text);
if (Num < 20)
{
if (generate.Length >= Num)
{
for (int i = Num; i > 0; i--)
{
name = generate.ElementAt(i);
listBox1.Items.Add(name); // Print it to list1
generate = generate.Where(s => s != name).ToArray(); // Delete name after using
}
}
else MessageBox.Show("Sorry, remaining names =" + generate.Length);
listBox2.Items.Clear();
listBox2.Items.AddRange(generate);
}
else MessageBox.Show("Max name is 20!");
}
Problem is that indexes in 20 elements array go from 0 to 19. In your code, you allow 20, wich makes an error
if (generate.Length >= Num)
You should remove = sign. Also, you should add = sign to for loop
for (int i = Num; i > 0; i--)
so you can include the first element of array (the one with index of 0).
Basically, if condition should look like this:
if (generate.Length > Num)
and for loop like this:
for (int i = Num; i >= 0; i--)
Try 19 instead of 20 because when you count elements in an array you start by zero.
this will let you place 20 in your textbox
Num = int.Parse(textBox1.Text);
if (Num <= 20)
{
if (generate.Length >= Num)
{
for (int i = Num - 1; i >= 0; i--)
{
name = generate.ElementAt(i);
listBox1.Items.Add(name); // Print it to list1
generate = generate.Where(s => s != name).ToArray(); // Delete name after using
}
}
else MessageBox.Show("Sorry, remaining names =" + generate.Length);
listBox2.Items.Clear();
listBox2.Items.AddRange(generate);
}
else MessageBox.Show("Max name is 20!");

Categories