Sort C# ListBox Items - c#

I'm using C# Adapter method, I add elements to a list and after that I call that list to fill a listbox, here is my button for do that:
private void button1_Click(object sender, EventArgs e) {
listCustomers.Items.Clear();
List < Customer > customers = CustomerList.GetCustomers();
List < CustomerSaldo > customersSaldo = CustomerListSaldo.GetCustomers();
int total = 0;
int totalCustomer = 0;
foreach(Customer customer in customers)
total++;
listCustomers.Items.Clear();
totalCustomer = total;
int x = totalCustomer;
foreach(CustomerSaldo customer2 in customersSaldo) {
if (x >= 1) {
listCustomers.Items.Add("Costumer ID # " + x + " is: " + customer2.Saldo);
x--;
}
}
}
This is what I get, it's ok but I want to know if exists a way to do this like this example:
Costumer #1 Saldo...
Costumer #2 Saldo...
Costumer #3 Saldo...
If you see my code I have a variable x, this variable is the total number of costumers, so I think that my sort has to start with this variable, but I don't know exactly how to do it, what can I do?

Reverse the list and start counting untill you reach the end:
//Reverse the list
customersSaldo.Reverse();
//Add new items
for(int i = 0; i < customers.Count; i++)
listCustomers.Items.Add(string.Format("Costumer ID # {0} is: {1}", (i+1).ToString(), customersSaldo[i].Saldo);

you can probably reverse (Using the Reverse method) your list "customersSaldo" before adding it, and then use the variable 'x' in increment order.
https://msdn.microsoft.com/en-us/library/b0axc2h2(v=vs.110).aspx

Related

Creating a highscore list in c#

I need to use arrays/lists for my assignment and thought of using one for my highscore list for my game in windows form.
Right now I'm using a regular int for my Score and I'm wondering how I can get this into an array for a highscore list on my highscore.cs
Current code for score in game.cs
int Score = 0;
Scorelabel.Text ="score:" + score;
if (Picturebox.Left < -180)
{
Picturebox.Left = 800;
Score++;*
Things I've tried:
namespace Game
{
public partial class Highscore : Form
{
public Highscore()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
int[] Highscore = new int[10];
for (int Score = 0; Score < 10; Score++)
{
textBox1.Text = new System.Windows.Forms.TextBox();
}
}
}
I tried to make the initial score int an array. I would end up getting the error:"Operator ++ cannot be applied to operand of type 'int[]'
Also tried to get my int into an array but would get the error that I can't convert ints to arrays.
What I want
I want my scores from the game.cs to show in a listbox on my highscore.cs that shows the top 10 scores descending from highest to lowest.
Let's imagine you've got 20 players and each one got some score.
As you decided to create an array of ints to store all scores, so do I:
int[] scores = new int[20];
For example, I fill that array with random unique scores from 10 to 100. You fill in your way:
int[] scores = new int[20];
Random rnd = new Random();
for (int i = 0; i < scores.Length; i++)
{
int score = 0;
// This loop used to generate new random int until it wouldn't be unique (wouldn't exist in array)
while (score == 0 || scores.Contains(score))
score = rnd.Next(10, 100);
scores[i] = score;
lblAllScores.Text += "Player #" + (i + 1) + " score: " + scores[i] + "\n";
}
I append each score and Player # (as number of iteration + 1) to some Label on Form to show all players and their scores. Something like this:
Now you (and I) want take top 10 scores (obviously in descending order, from highest to lowest). Here the keywords are Take and Descending order. In C# through System.Linq namespace provided such pretty extension methods like Take and OrderByDescending. And seems they can give us desired result if we use it properly.
I (and you) creating a new array of ints to store only Top 10 Scores. Then a take initial array scores and use OrderByDescending method to sort values in it from highest to lowest. (x => x) provided as selector to determine key by which method should order values - in our case by value itself. And then I use Take(10) method to take first 10 scored from that sorted array - this is our Top 10 Scores:
int[] top10Scores = scores.OrderByDescending(x => x).Take(10).ToArray();
And all I need to do - put this into Form, which I can do by simple iteration on top10Scores array with for loop. But I (and probably you) want to know what Player has that score. Upper we use (index of array + 1) as Player Number. And we know that scores are unique for each Player. Than now we can take the score value from top10Scores array and try to find its index in source scores array with Array.FindIndex method:
for (int i = 0; i < top10Scores.Length; i++)
{
int playerNumber = Array.FindIndex(scores, score => score == top10Scores[i]) + 1;
lblTop10Scores.Text += "Player #" + playerNumber + " score: " + top10Scores[i] + "\n";
}
And at our Form we have this:
Complete code:
private void ScorePlayers()
{
int[] scores = new int[20];
Random rnd = new Random();
for (int i = 0; i < scores.Length; i++)
{
int score = 0;
while (score == 0 || scores.Contains(score))
score = rnd.Next(10, 100);
scores[i] = score;
lblAllScores.Text += "Player #" + (i + 1) + " score: " + scores[i] + "\n";
}
int[] top10Scores = scores.OrderByDescending(x => x).Take(10).ToArray();
for (int i = 0; i < top10Scores.Length; i++)
{
int playerNumber = Array.FindIndex(scores, score => score == top10Scores[i]) + 1;
lblTop10Scores.Text += "Player #" + playerNumber + " score: " + top10Scores[i] + "\n";
}
}
Please note, that this is only a sketch and example to demonstrate how to use OrderByDescending and Take extension methods to get first 10 elements of sorted from highest to lowest value collection. In real application you probably will have at least simple Dictionary<string, int>, where would be stored player name (as string) and his score (as int). Or, more likely, it would be a model class called Player with Name and Score properties and each Player would be stored in some List<Player>:
public class Player
{
public string Name { get; set; }
public int Score { get; set; }
}
Hope you can find your solution and this example would be helpful for you.

Adding values to a list box from array WITH text

I'm adding values from a file to an array and then adding those values to a list box in a form. I have methods performing calculations and everything is working great, but I'd like to be able to use a loop and insert the year prior to the values I am inserting into the list box. Is there a way to use the .Add method and include a variable which will be changing in this? Something like populationListbox.Items.Add(i, value); if i is my loop counter? Code is below so I'd like first line in the list box to have the year I specify with my counter, followed by the population. Like this, "1950 - 151868". As of now it only displays the value 151868. Thanks!
const int SIZE = 41;
int[] pops = new int[SIZE];
int index = 0;
int greatestChange;
int leastChange;
int greatestYear;
int leastYear;
double averageChange;
StreamReader inputFile;
inputFile = File.OpenText("USPopulation.txt");
while (!inputFile.EndOfStream && index < pops.Length)
{
pops[index] = int.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach (int value in pops)
{
**populationListbox.Items.Add(value);**
}
greatestChange = greatestIncrease(pops) * 1000;
leastChange = leastIncrease(pops) * 1000;
averageChange = averageIncrease(pops) * 1000;
greatestYear = greatestIncreaseyear(pops);
leastYear = leastIncreaseyear(pops);
greatestIncreaselabel.Text = greatestChange.ToString("N0");
leastIncreaselabel.Text = leastChange.ToString("N0");
averageChangelabel.Text = averageChange.ToString("N0");
greatestIncreaseyearlabel.Text = greatestYear.ToString();
leastIncreaseyearlabel.Text = leastYear.ToString();
Like this?
int i = 1950;
foreach (int value in pops)
{
populationListbox.Items.Add(i.ToString() + " - " + value);
i++;
}
Your life will be a lot easier if you stop trying to program C# as if it were 1980s C and use the power of it's Framework:
var pops = File.ReadLines("USPopulation.txt").Select(int.Parse);
populationListbox.Items.AddRange(pops.Select((p,i) => $"{i} - {p}"));

C# GUI application that stores an array and displays the highest and lowest numbers by clicking a button

Background:This is updated from 13 hours ago as I have been researching and experimenting with this for a few. I'm new to this programming arena so I'll be short, I'm teaching myself C# And I'm trying to learn how to have integers from a user's input into a textbox get calculated from a button1_Click to appear on the form. Yes, this is a class assignment but I think I have a good handle on some of this but not all of it; that's why I'm turning to you guys.
Problem:
I'm using Microsoft Visual Studio 2010 in C# language, Windows Forms Application and I need to create a GUI that allows a user to enter in 10 integer values that will be stored in an array called from a button_Click object. These values will display the highest and lowest values that the user inputted. The only thing is that the array must be declared above the Click() method.
This is what I have come up with so far:
namespace SmallAndLargeGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inputText_TextChanged(object sender, EventArgs e)
{
this.Text = inputText.Text;
}
public void submitButton_Click(object sender, EventArgs e)
{
int userValue;
if(int.TryParse(inputText.Text, out userValue))
{
}
else
{
MessageBox.Show("Please enter a valid integer into the text box.");
}
int x;
x = Convert.x.ToString();
int squaredResults = squared(x);
int cubedResults = cubed(x); squared(x);
squaredLabel.Text = x.ToString() + " squared is " + squaredResults.ToString();
cubedLabel.Text = x.ToString() + " cubed is " + cubedResults.ToString();
}
public static int squared(int x)
{
x = x * x;
return x;
}
public static int cubed(int x)
{
x = x * squared(x);
return x;
}
}
}
Now I can't run this program because line 38 shows an error message of: 'System.Convert' does not contain a definition for 'x' Also I still have to have an array that holds 10 integers from a textbox and is declared above the Click() method. Please guys, any help for me? This was due yesterday.
This looks like homework, so you should try a bit more than that. Here is what you could do: parse the string (say it's a comma-separated list of numbers), cast each value to int and populate your array. You can either call .Max() / .Min() methods or loop through the values of the array and get the max / min value. Here is a bit of code:
int n = 10;
int[] numbers = (from sn in System.Text.RegularExpressions.Regex.Split(inputText.Text, #"\s*,\s*") select int.Parse(sn)).ToArray();
int max = numbers.Max();
int min = numbers.Min();
//int max = numbers[0];
//int min = numbers[0];
//for(int i = 1; i < n; i++)
//{
// if(max < numbers[i])
// {
// max = numbers[i];
// }
// if(min > numbers[i])
// {
// min = numbers[i];
// }
//}
This in all probability being a homework I will not provide entire solution but just provide a hint.
Task to me seems to be to some how accept 10 integers and then show smallest and largest of them. For this there is no need to maintain an array (off-course only if maintaining an array is itself not part of the problem). You just need to keep track of current minimum and current maximum.
As and when you receive an input compare it with the current minimum and maximum and update them accordingly. e.g.
if(num < curr_min) curr_min = num;

How to check the missing element in the sequence

I am doing a project related to payroll where i will have some payperiodnumbers for each and every payroll that has been runned. I will show all the payrolls in a grid view with the corresponding pay period numbers.
Assume i get the following results when i binded to grid
Now from the grid if i select 1 and click on delete i would like to show an error message stating you have to delete max pay period first.
Like that if i had my max pay period number as 7 and if user selects 1,2,3,4,5,6 and try to delete i would like to display the same error. I am saving the selected ID's in a arraylist so can any one help me how can i check for my condition as specified. I can get the maximum payperiodid using the query but the remaining code i would like to do.
I am using 2.0 so no point of using LINQ here. Can any one help me
As Azodious pointed i am showing some condition that should work and some not
If max number is 7 and if i select 1,5,7 i would like to display an error message.
If i select 5,6,7 then it should delete that.
Something like this:
selectedNumbers.Sort();
selectedNumbers.Reverse();
int maxPeriodNumber = 5; // This you know
int lastValue = (int)selectedNumbers[0];
if (lastValue < maxPeriodNumber)
{
// Highest selected number is smaller than required, warn user or throw exception
return;
}
foreach (int val in selectedNumbers)
{
if (val < (lastValue - 1))
{
// There is a gap in the numbering, warn user or throw exception
return;
}
lastValue = val;
}
// When you end up here, everything is ok and you can delete the items whose numbers are in the list
A simple logic to display missing numbers
ArrayList a = new ArrayList();
List<int> lst = new List<int>();
lst.Add(1);
lst.Add(3);
lst.Add(5);
int fst = (int)lst[0];
int last = 0;
for (int i = 0; i < lst.Count; i++)
{
last = (int)lst[i];
}
for (int k = fst; k <= last; k++)
{
if (k == fst | k == last)
{
}
else
{
a.Add(k);
a.Add(" ");
}
}
Label1.Text = "Missing Numbers are" + " " + System.String.Concat(a.ToArray());

mulit select listbox in wpf

how i can select five items in the single click on the list box??
if i click any item, i just want to +2 and -2 from the selected index. so my single click need to select five items in the listview.
Am using C#(WPF).
I am not sure what you want to do exactly, but trying. =)
Have a look at the Click event of the ListBox. You can do anything in there, including selecting five items of your choice. You can do it like this (untested, but gives you an idea):
int sindex = listBox1.SelectedIndex;
listBox1.SelectedItems.Clear();
for(int i = Math.Max(sindex - 2, 0); i < Math.Min(sindex + 2, listBox1.Items.Count()), i++)
{
listBox1.SelectedItems.Add(listBox1.Items[i]);
}
Another thing would be setting the SelectionMode to Multiple or Extended. Does this result in the behaviour you are looking for?
have a look at selectionchanged event, and get the index of the selected item and make it +2 and -2
i tried it like this and it works:
void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int idx = list.SelectedIndex;
int startIdx = idx - 2;
int endIdx = idx + 2;
if (startIdx < 0)
{
startIdx = 0;
}
if (endIdx >= list.Items.Count)
{
endIdx = list.Items.Count-1;
}
for (int i = startIdx; i <= endIdx; i++)
{
if (i != idx)
{
list.SelectedItems.Add(list.Items[i]);
}
}
}
one problem with this code is you can still use ctrl to select another item so it makes the selecteditems count increased

Categories