Update data in a listbox from another form - c#

I'm creating a program that maintains student scores. I've created a class called students that stores the data and displays it in a list box. Once the user clicks Add a new form (frmAddStudent) loads that allow them to add the user by name and their scores and display it in the list box in the main form. It also allows the update/delete functions. I can successfully add students to the list and edit them, but when I press the ok button in the update students form I get the error
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'
I looked up that this means its thrown when the value of an argument is outside the allowable range of values as defined by the invoked method, but not sure how it applies here. My value I enter when updating is within range.
Source code below
https://github.com/Triptonix/Student.git
frmUpdateStudent.cs
private void UpdateButton_Click_1(object sender, EventArgs e) //open update form for current student
{
Student Form1 = new Student();
Form1.Name = StudentName.Text;
parentForm.UpdateStudent(index, Form1);
Close();
}
Form1.cs
public List<Student> studentList = new List<Student>();
public Student GetStudent(int id) //Get student index
{
return studentList[id];
}
public void UpdateStudentList()
{
students.DataSource = null;
students.DataSource = studentList;
students.DisplayMember = "Name";
}
public bool UpdateStudent(int originalIndex, Student studentToEdit)
{
try
{
Student student = GetStudent(originalIndex); //select index of student
student.Name = studentToEdit.Name; //name of student
studentList.RemoveAt(originalIndex); //remove the student at the index selected
studentList.Insert(originalIndex, student); //insert new student at index.
UpdateStudentList(); //update student list
}
catch { return false; }
return true;
}
Student.cs
public class Student
{
public List<int> Scores = new List<int>();
public string Name { get; set; }
public bool AddScore(int score)
{
try
{
Scores.Add(score);
}
catch { return false; }
return true;
}
public List<int> GetScores()
{
return Scores;
}
public int GetScoreAt(int index)
{
return (int)Scores[index];
}
public int GetScoreTotal()
{
int sum = 0;
foreach (int score in Scores)
{
sum += score;
}
return sum;
}
public int GetScoreCount()
{
return Scores.Count;
}
public int GetScoreAverage()
{
return GetScoreTotal() / GetScoreCount();
}
public void DestroyScores()
{
Scores = new List<int>();
}
}
frmUpdateStudent
public partial class frmUpdateStudent : Form
{
private Form1 parentForm; //main form
private Student studentToEdit; //student list
private int index; //index
public frmUpdateStudent(Form1 parentForm, int index) //update parent form (Form1) with the new student and scores
{
this.parentForm = parentForm;
this.index = index;
studentToEdit = this.parentForm.GetStudent(index);
InitializeComponent();
StudentName.Text = studentToEdit.Name;
UpdateScoreDisplay();
}
public void AddScoreToStudent(int value) //add score to current student and display in the list
{
studentToEdit.AddScore(value);
UpdateScoreDisplay();
}
public void UpdateScoreAtIndex(int id, int value) //update a score selected from the list
{
studentToEdit.GetScores()[id] = value;
UpdateScoreDisplay();
}
public int GetScoreAtIndex(int id) //get the score index
{
return studentToEdit.GetScoreAt(id);
}
private void UpdateScoreDisplay() //update the score display list
{
CurrentScores.DataSource = null;
CurrentScores.DataSource = studentToEdit.GetScores();
}
private void AddScoreButton_Click(object sender, EventArgs e) //open the add score form
{
frmAddScore addScoreForm = new frmAddScore(this);
addScoreForm.Show();
}
private void RemoveScoreButton_Click_1(object sender, EventArgs e) //remove a score from current index and update display list
{
studentToEdit.GetScores().RemoveAt(CurrentScores.SelectedIndex);
UpdateScoreDisplay();
}
private void ClearScoresButton_Click_1(object sender, EventArgs e) //clear all scores
{
studentToEdit.DestroyScores();
UpdateScoreDisplay();
}
private void CloseButton_Click_1(object sender, EventArgs e)
{
Close(); //close form
}
private void UpdateButton_Click_1(object sender, EventArgs e) //open update form for current student
{
Student Form1 = new Student();
Form1.Name = StudentName.Text;
parentForm.UpdateStudent(index, Form1);
Close();
}
private void UpdateScoresButton_Click(object sender, EventArgs e)
{
frmUpdateScore updateScoreForm = new frmUpdateScore(this, CurrentScores.SelectedIndex);
updateScoreForm.Show();
}
}

So turns out the index of my list was -1 when I was trying to call it. I set the SelectedIndex as a local variable then called it. I guess the selected index had to be checked before I could execute it. This the code I fixed.
private void students_SelectedIndexChanged_1(object sender, EventArgs e) {
_selectedIndex = students.SelectedIndex;
if (_selectedIndex > -1)
{
Student student = GetStudent(_selectedIndex); //select index from list
Student students = GetStudent(_selectedIndex); //select index from list
ScoreTotalTextBox.Text = student.GetScoreTotal().ToString(); //show Score Total to box
ScoreCountTextBox.Text = student.GetScoreCount().ToString(); //show Score Count to box
ScoreAverageTextBox.Text = student.GetScoreAverage().ToString(); //show Score Average to box
}
}

Related

How to add text from textbox into a list

I have create a empty list which will get used when the user enters new tracks and my interface has listbox and a texbox and add and remove button.
My aim is to when i add a new item into the listbox same button use the function to add that item to a list rather them just adding to a listbox and not storing it.
trackListbox.Items.Add(newTracktextBox.Text);
List<Songs> NewSongs = newTracktextBox.Text ().ToList(); ; this is not correct
Any different ideas?
class Songs
{
private string trackName;
private int trackLength;
public Songs (string trackName, int trackLength)
{
this.trackName = trackName;
this.trackLength = trackLength;
}
}
Try this
Songs objSong = new Songs(newTracktextBox.Text,0); // define your length instead of 0
List<Songs> NewSongs = new List<Songs>();
NewSongs.Add(objSong);
It's good practice to name the class Song instead of Songs since it will represent only one song.
With adding songs manually to the listBox
private List<Song> SongList;
public Form1()
{
InitializeComponent();
SongList = new List<Song>();
}
private void button1_Click(object sender, EventArgs e)
{
Song song = new Song(newTracktextBox.Text, 100);
SongList.Add(song);
listBox1.Items.Add(song); // The trackName will be shown because we are doing a override on the ToString() in the Song class
}
class Song
{
private string trackName;
private int trackLength;
public Song(string trackName, int trackLength)
{
this.trackName = trackName;
this.trackLength = trackLength;
}
public override string ToString()
{
return trackName;
// Case you want to show more...
// return trackName + ": " + trackLength;
}
}
With automatic binding by using a BindingList<Song>
private BindingList<Song> SongList;
public Form1()
{
InitializeComponent();
// Initialise a new list and bind it to the listbox
SongList = new BindingList<Song>();
listBox1.DataSource = SongList;
}
private void button1_Click(object sender, EventArgs e)
{
// Create a new song and add it to the list,
// the listbox will automatically update accordingly
Song song = new Song(newTracktextBox.Text, 100);
SongList.Add(song);
}
class Song
{
private string trackName;
private int trackLength;
public Song(string trackName, int trackLength)
{
this.trackName = trackName;
this.trackLength = trackLength;
}
public override string ToString()
{
return trackName;
}
}
Result
Your newTracktextBox variable is not an object of type Song.
You should create a new object of type Song with the text that's in newTracktextBox and add the new object to the list
public class Songs{
String TrackName;
int TrackLength;
public Songs(string trackName, int trackLength){
this.TrackName = trackName;
this.TrackLength = trackLength;
}
//methods
}
make a list of songs
List<Songs> NewSongs = new List<Songs>();
add the new song to the list by
int tracklength = 50; // set the tracklength where you need
NewSongs.Add(new Songs(TextBox.Text.ToString(),tracklegnth));
Note that the ToString() method maybe is redudant.
hope i helped

C# Forms add text to textbox from other class

I have a C# Form called Form1.cs and a Class in the same project called RandWord.cs.
Now I want to add text to the textbox (tbRandom) from the class.
I added the following code to Form1.cs:
public TextBox tbRandom;
And the following code to the class:
public RandWord()
{
//get linecount
int linesGerman = File.ReadAllLines(pathGerman).Length;
int linesFrance = File.ReadAllLines(pathFrance).Length;
//check if same linecount
if (linesGerman == linesFrance)
{
//new random int
Random rnd = new Random();
int rndLine = rnd.Next(1, File.ReadAllLines(pathGerman).Length);
//write to Form1's Textbox tbWord
f1.tbRandom.Text = rndLine.ToString();
MessageBox.Show(rndLine.ToString());
}
}
The messagebox is just there to prove that the Int is not empty. But the textbox won't display anything. There is no Exception aswell. The class is called by a button ( RandWord(); )
Any ideas?
In you From1 :
public TextBox tbRandom =new TextBox() ;
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.Add(tbRandom);
}
public string TextBoxTxt {
get { return txtText1.Text; }
set { txtText1.Text = value; }
}
//Your button RandWord
private void RandWord_Click(object sender, EventArgs e)
{
RandWord(this);
}
Your class RandWord :
public RandWord(Form f1)
{
//get linecount
int linesGerman = File.ReadAllLines(pathGerman).Length;
int linesFrance = File.ReadAllLines(pathFrance).Length;
//check if same linecount
if (linesGerman == linesFrance)
{
//new random int
Random rnd = new Random();
int rndLine = rnd.Next(1, File.ReadAllLines(pathGerman).Length);
//write to Form1's Textbox tbWord
f1.TextBoxTxt = rndLine.ToString();
MessageBox.Show(rndLine.ToString());
}
}
You can write a contractor method for your class and pass the TextBox to it, and you can access the TextBox from there.
class GenerateRandomWord
{
TextBox _t;
public GenerateRandomWord(TextBox t)
{
_t = t;
}
public void RandWord()
{
_t.Text = "Something!";
}
}

Get/Set store multiple values for numerous buttons c#

I am trying to store multiple values from numerous buttons so I can return values of two or more things e.g. if chocolate and vanilla clicked both prices and names can be returned. I will also need to make calculations on the data set later. Whenever I return the data only the most recent values return rather than all of those I have selected.
private void VanillaBtn_Click(object sender, RoutedEventArgs e)
{
items.Price = 450;
items.Name = "Vanilla"
}
private void ChocolateBtn_Click(object sender, RoutedEventArgs e)
{
items.Price = 500;
items.Name = "Chocolate";
}
This is my class, any help or tips would be appreciated.
class Items
{
private int thePrice;
private string theName;
public int Price
{
get
{
return thePrice;
}
set
{
thePrice = value ;
}
}
public string Name
{
get
{
return theName;
}
set
{
theName = value;
}
}
Keep a list of whatever was clicked.
private List<Items> selectedItems = new List<Items>();
So, every time something is clicked, you store the object in the list defined above.
private void VanillaBtn_Click(object sender, RoutedEventArgs e)
{
var newItem = new Items();
newItem.Price = 450;
newItem.Name = "Vanilla";
selectedItems.Add(newItem);
}

asp.net c# using session data to output more data

Ok guy,
i have made a simple program that has a web form where you fill in details fruit name, kg and cal count. i have then used session variables to get the fruit name from the form on default page and display them on about page in a drop down menu. that's all working fine, what i cant seem to work out is on the about page how to get it so the user selects a item from the drop down (created from form on default page) then enter a int how many they want (in text box) and have there selection and amount output on a list box on about page. il post the code i have so far any help would be much appreciated.
default page
public class Fruit
{
private string fName;
private int grams, calsPerGram;
private bool edible;
public Fruit(string n, int g, int c, bool e)
{
grams = g;
calsPerGram = c;
edible = e;
fName = n;
}
public int totalCalories()
{
return grams * calsPerGram;
}
public string getFruitInfo()
{
string s;
if (edible == true)
{
s = fName + " is yummy and it has " + totalCalories() +
"calories";
}
else
{
s = "Hands off! Not edible";
}
return s;
}
}
public partial class _Default : System.Web.UI.Page
{
List<Fruit> myBasket;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
myBasket = new List<Fruit>();
Session["listSession"] = myBasket;// seassion start
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
// Session["Fruitname"] = TbxName.Text; // my session i have made
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
MyFruit.Add(TbxName.Text);
Session["Fruitname"] = MyFruit;
abc.Items.Clear();
Fruit f = new Fruit(TbxName.Text, int.Parse(TbxWeight.Text),
int.Parse(TbxCal.Text), CheckBox1.Checked);
myBasket = (List<Fruit>)Session["listSession"]; // session used
myBasket.Add(f);
foreach (var item in myBasket)
{
abc.Items.Add(item.getFruitInfo()); // List box used
}
}
public List<string> MyFruit { get; set; }
}
About page
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
DropDownList1.DataSource = MyFruit;
DropDownList1.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Drinklabel.Text = "Your Chosen Beverage is A " + DropDownList1.SelectedValue.ToString() + " Drink.";
}
public List<string> MyFruit { get; set; }
}
You do not necessarily need a separate class for calculating cost, but I recommend that you use a Label to display the selected fruit, amount desired and total price, like this in your About page:
Create a Button with Calculate text that has a click event handler, a calculatePrice method, a TextBox for quantity and a Label for display, like this:
protected void ButtonCalculate_Click(sender object, EventArgs e)
{
decimal total = calculatePrice(DropDownList1.SelectedItem.Text,
TextBoxQuantity.Text.Trim());
LabelResult.Text = "You would like " + TextBoxQuantity.Text.Trim() +
DropDownList1.SelectedItem.Text + "(s) for a total of $" +
total.ToString();
}
private decimal calculatePrice(string fruitName, int quantity)
{
// Ask the database for the price of this particular piece of fruit by name
decimal costEach = GoToDatabaseAndGetPriceOfFruitByName(fruitName);
return costEach * quantity;
}

Am I missing an if statement?

thanks in advance for any help!
A bit of background basically I am building an application that stores vehicles (cars,truck,buses), I have a vehicle superclass and all the individual classes (car.cs, truck.cs, minibus.cs) inherit from this super class.
I also have a class called 'fleet' that I would like to add the vehicles to an then display the results in a list box.
I have everything else working but I cannot get the trucks and minibus's to update and display on the list box like the cars do.
Here is my fleet class which includes the car.cs; and it works fine and the data taken from the car form gets added and displayed in the listbox.
class Fleet
{
private List<Vehicle> theFleet = new List<Vehicle>();
public List<Vehicle> fleet
{
get
{
return theFleet;
}
}
public void deleteFromFleet(Vehicle aCar)
{
theFleet.Remove(aCar);
}
public void addToFleet(Vehicle aCar)
{
theFleet.Add(aCar);
}
}
Here is my main form, that has the list box on it:
public partial class FrmHireCo : Form
{
private Fleet myFleet = new Fleet();
private ClientList mycustomer = new ClientList();
//Fleet object used to store cars
public FrmHireCo()
{
//Default constructor
InitializeComponent();
}
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Car c in myFleet.fleet)
{
string line = "Car: " + c.make+" " + c.colour;
lstFleet.Items.Add(line);
}
}
private void updateClientList()
{
customers.Items.Clear();
foreach (Customer c in mycustomer.clientlist)
{
string line = "Customer: " + c.name + " " + c.address;
customers.Items.Add(line);
}
}
private void btnAddCar_Click(object sender, EventArgs e)
{
//Add a new car
FrmCar carGui = new FrmCar(); //Form used to add new car
carGui.ShowDialog();
Car myCar = carGui.car; //Get new car from form
myFleet.addToFleet(myCar); //Add to fleet list
updateFleetList(); //Uodate fleet list
}
private void lstFleet_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstFleet.SelectedIndex > -1)
{
int index = lstFleet.SelectedIndex;
Car myCar = myFleet.fleet.ElementAt(index);
FrmCar carGui = new FrmCar();
carGui.car = myCar;
carGui.Show();
}
}
private void btnCustomer_Click(object sender, EventArgs e)
{
FrmCustomer customerGui = new FrmCustomer();
customerGui.ShowDialog();
Customer mycustomer = customerGui.customer;
mycustomer.addToClientList(mycustomer);
updateFleetList();
}
private void customers_SelectedIndexChanged(object sender, EventArgs e)
{
if (customers.SelectedIndex > -1)
{
int index = customers.SelectedIndex;
Customer myCustomer = mycustomer.clientlist.ElementAt(index);
FrmCustomer customerGui = new FrmCustomer();
customerGui.customer = myCustomer;
customerGui.Show();
}
}
}
Cheers for any help!
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Vehicle c in myFleet.fleet)
{
string line = "Car: " + c.make+" " + c.colour;
lstFleet.Items.Add(line);
}
}
You should include all vehicles.
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Vehicle v in myFleet.fleet)
{
lstFleet.Items.Add(v);
}
}
Also, just override ToString in all your Vehicle subclasses and the ListBox will use that inherently; this way not every Vehicle needs a Make or Color property.

Categories