Adding all values selected from the Listbox - c#

So this is how far I have gotten I am not really sure.
So I populated my listbox1 with values such as 1.2, 1.3
So how do I add all the selected values of my listbox and caculate the average?
If you could help me I be very thankful.
List<double> doubleList = new List<double>();
private void btnGetAverage_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
}
}

First make the SelectionMode property of your listbox as MultiSimple. Then try this code.
double total = 0;
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
total += Double.Parse(listBox1.SelectedItems[i].ToString());
}
MessageBox.Show("The average is: " + total / listBox1.SelectedItems.Count);

You can you the Average method:
List<double> doubleList = new List<double>();
private void btnGetAverage_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
var myList = listbox1.SelectedItems as List<double>;
return myList.Average();
}
}

Add your list of doubles to your ListBox like this:
listBox1.DataSource = doubleList;
Then this will get you the average of only selected items:
var average = listBox1.SelectedItems.Cast<double>().Average();

Related

Get specific listview rows based on condition

I have a listview with diffrent entries (see figure (A). I would like to extract some specific rows based on a condition. So far, i have this code:
private void Button2_Click(object sender, EventArgs e)
{
ArrayList listing = new ArrayList();
for (int i = 0; i < listView2.Items.Count; i++)
{
string columnOne = listView2.Items[i].Text;
string columnTwo = listView2.Items[i].SubItems[1].Text;
int numb = int.Parse(listView2.Items[i].SubItems[2].Text);
string columnThree = listView2.Items[i].SubItems[3].Text;
if(numb >= 2)
{
listing.Add($"{columnOne},{columnTwo},{numb},{columnThree}");
}
}
foreach (string item in listing)
{
listView2.Items.Clear();
ListViewItem listItem = new ListViewItem();
var separ = item.Split(',');
listItem.Text = separ[0].Trim();
listItem.SubItems.Add(separ[1]);
listItem.SubItems.Add(separ[2]);
listItem.SubItems.Add(separ[3]);
listView2.Items.Add(listItem);
}
}
I get figure (B), but normally i should get figure (C). How can this be achieved?
you shouldn't clear listview in foreach loop. do it once:
listView2.Items.Clear();
foreach (string item in listing)
{
// listView2.Items.Clear();
ListViewItem listItem = new ListViewItem();
var separ = item.Split(',');
listItem.Text = separ[0].Trim();
listItem.SubItems.Add(separ[1]);
listItem.SubItems.Add(separ[2]);
listItem.SubItems.Add(separ[3]);
listView2.Items.Add(listItem);
}
Removing the non matching items from the list makes more sense here. For your problem, execute a backward loop, try to convert the text of the third subitem to integer value using the int.TryParse method, and remove the ListViewItem if the value is less than 2.
private void button2_Click(object sender, EventArgs e)
{
for (var i = listView2.Items.Count - 1; i >= 0; i--)
{
if (int.TryParse(listView2.Items[i].SubItems[2].Text, out var num) && num < 2)
{
listView2.Items.RemoveAt(i);
}
}
}
Yet, if you want to get a list of matching items:
// +
using System.Collections.Generic;
private void button2_Click(object sender, EventArgs e)
{
var items = new List<ListViewItem>();
for (var i = 0; i < listView2.Items.Count; i++)
{
if (int.TryParse(listView2.Items[i].SubItems[2].Text, out var num) && num >= 2)
{
items.Add(listView2.Items[i]);
}
}
// ...
}
Or LINQ way:
// +
using System.Linq;
private void button2_Click(object sender, EventArgs e)
{
var items = listView2.Items.Cast<ListViewItem>()
.Where(x => int.TryParse(x.SubItems[2].Text, out var num) && num >= 2)
.ToList();
// ...
}
As a side note, using the ArrayList class is not recommended, use the List<T> class instead.

How to get sum of selected DataGrid values in a C# WPF app?

I have a C# WPF app, and my goal is to get the sum of selected row values from a DataGrid, and set a textbox with this total. This sum calculation is triggered by an event that detects when the selected items have changed.
The problem is that when I select many rows at once or select all with Ctrl + A, I get unpredictable sum values.
To troubleshoot, I bound the datagrid with 100 rows, each with an amount of 1. I then selected all items with Ctrl + A. The total sum should be 100, but it caps at 7 or 8 units.
Below is what I have so far. Anyone see the problem?
private void DgDailyTransactions_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
decimal sum = 0;
for (int i = 0; i < dgDailyTransactions.SelectedItems.Count; i++)
{
TextBlock tb = dgDailyTransactions.Columns[1].GetCellContent(dgDailyTransactions.SelectedItems[i]) as TextBlock;
if (tb != null)
{
sum += Convert.ToDecimal(tb.Text);
}
}
tbxSelectedDailyTransactionsTotal.Text = sum.ToString();
}
Suppose your class looks like this:
public class Sales
{
public int Order { get; set; }
public decimal Amount { get; set; }
}
Make a simple method as under:
private void FindAmount()
{
decimal totalSum = 0;
//Add amounts of selected
if (MyDTGRID.SelectedItems.Count > 0)
{
for (int i = 0; i <= dgDailyTransactions.SelectedItems.Count - 1; i++)
{
Sales sales = dgDailyTransactions.SelectedItems[i] as Sales;
decimal amount = sales.Amount;
totalSum += amount;
}
}
myTextBlock.Text = totalSum.ToString();
}
Simply call the method in your selectedCellsChanged Event
private void DgDailyTransactions_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
FindAmount();
}
I hope this helps.
for the sum method you can do it using linq (if you don't know I strongly advise you to learn linq, very strong tool in C#), also would advise you to use MVVM, will make your code much easier to debug in future :
private void dgDailyTransactions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
List<Sales> myList=dgDailyTransactions.SelectedItems.Cast<Sales>();
decimal totalSum = 0;
if (myList.Count() > 0)
{
totalSum = myList.Sum(item => item.Amount);
}
myTextBlock.Text = totalSum.ToString();
}
in MVVM (if you use it) you would need just that line in Model :
private void dgDailyTransactions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
contexte.SelectedSales= new ObservableCollection<Sales>(dgDailyTransactions.SelectedItems.Cast<Affaire>());
}
then you use formula in your ViewModel in set section of SelectedSales

c# how can i get my listbox item and add it quickly when i pressed checklistboxes

Hello I am still confuse to this how can I get my listbox items and when I click every checklistboxes and I want to add the numbers and display in the textbox. for example I check the checklistbox index 1 which contains 300 it display in the textbox. Then I check also my index 2 of checkboxlist contains 100 then it display 400. Then if I check my index 3 of my checkboxlist contains 200 it display 600 in the checkbox.
My code:
namespace ggg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
textBox1.Clear();
foreach (string s in checkedListBox1.CheckedItems)
listBox1.Items.Add(s);
foreach (int i in checkedListBox1.CheckedIndices)
{
if (i == 0)
{
listBox2.Items.Add(300);
decimal total = 300;
textBox1.Text += total;
}
if (i == 1)
{
listBox2.Items.Add(100);
decimal total = 100;
textBox1.Text += total;
}
if (i == 2)
{
listBox2.Items.Add(200);
decimal total = 200;
textBox1.Text += total;
}
}
}
}
}
you can sum listbox items as this . After , you can set the total to textbox
int total = 0;
for (int i = 0; i < listBox2.Items.Count; i++)
{
total = total+ int.Parse(listBox2.Items[i].ToString());
}
textBox1.Text = total.ToString();
This code might get your job done. There are still better ways to do what you are looking for. But, this can be a good solution too! Considering your textbox name as myTextBox:
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int sum = 0; // Add a variable to capture the sum
listBox1.Items.Clear();
listBox2.Items.Clear();
textBox1.Clear();
foreach (string s in checkedListBox1.CheckedItems)
listBox1.Items.Add(s);
foreach (int i in checkedListBox1.CheckedIndices)
{
if (i == 0)
{
listBox2.Items.Add(300);
sum += 300; // Add the value to sum
}
if (i == 1)
{
listBox2.Items.Add(100);
sum += 100; // Add the value to sum
}
if (i == 2)
{
listBox2.Items.Add(200);
sum += 200; // Add the value to sum
}
}
// Finally, show the sum in text box
myTextBox.Text = sum.ToString();
}

Min and max button and label

I'm trying to build a exam grader using C#. I'm new to this and don't know very much. What code would I use to add min and max buttons and to add a label stating whether it's a min or max?
private void btnAdd_Click(object sender, EventArgs e)
{
int points;
try
{
points = int.Parse(txtPoints.Text);
lstPoints.Items.Add(points);
txtPoints.Clear();
txtPoints.Focus();
if (lstPoints.Items.Count == 12)
{
txtPoints.Enabled = false;
btnAdd.Enabled = false;
}
if (lblResult.Text != "")
{
lblResult.Text = "";
}
}
catch
{
MessageBox.Show("Please enter only whole numbers");
txtPoints.Clear();
txtPoints.Focus();
}
}
private void btnAvg_Click(object sender, EventArgs e)
{
double total = 0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
total += (int)lstPoints.Items[i];
}
total /= lstPoints.Items.Count;
lblResult.Text = total.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
lstPoints.Items.Clear();
txtPoints.Enabled = true;
btnAdd.Enabled = true;
}
}
}
hope this works
private void getMax()
{
int max=0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
if(max<(int)lstPoints.Items[i])
{
max=(int)lstPoints.Items[i];
}
}
lblResult.Text = max.ToString();
}
}
private void getMin()
{
int min=(int)lstPoints.Items[0];
for (int i = 1; i < lstPoints.Items.Count; i++)
{
if(min>(int)lstPoints.Items[i])
{
min=(int)lstPoints.Items[i];
}
}
lblResult.Text = min.ToString();
}
}
There are two possiblities as I see:
1) When you are writing this:
lstPoints.Items.Add(points);
Instead of adding to List(Of Integer) use SortedList. So the
list will always have the sorted result sets.
2) Use Array.Sort() to sort the records.
Once you have sorted records the first one is the minimum and the last one is the maximum (Assuming sorted in ascending order).
Take out two buttons and placed on the form, set Text Property from property window to Min and Max respectively and in event handler handle the Click event and pick the relevant resultset from lstPoints array.
Hope it helps!

Find the highest number in array , using while or for?

Please a i have a Questions , I need find the higghest value in array. To the array will people write name (textbox1) and money (texbox2). I have 2 buttons first button is save to the array and second write the name with the biggest money.
Code for save:
string[] name = new string[50];
int items = 0;
int[] money = new int[50];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Convert.ToInt32(textBox2.Text);
}
catch
{
name[items] = textBox1.Text;
money[items] = Int32.Parse(textBox2.Text);
items++;
}
}
And to the button2 need search the biggest value and write name! Please help me
private void button2_Click(object sender, EventArgs e)
{
int maxIndex = 0;
for(int i = 0; i < 50; i++)
{
if (money[i] > money[maxIndex])
maxIndex = i;
}
MessageBox.Show(name[maxIndex] + " has biggest value " + money[maxIndex]);
}
To get the Max int from your array you can use IEnumerable.Max:
money.Max();
But there could be more than one name with the same high money value, perhaps you need to handle this also, I think Dictionary would be your best option
private Dictionary<string, int> Names = new Dictionary<string, int>();
private void button1_Click(object sender, EventArgs e)
{
int value = 0;
if (int.TryParse(textBox2.Text, out value))
{
if (!Names.ContainsKey(textBox1.Text))
{
Names.Add(textBox1.Text, value);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Names.Any())
{
int maxMoney = Names.Max(v => v.Value);
var names = Names.Where(k => k.Value.Equals(maxMoney));
foreach (var name in names)
{
// Names with the highest money value
}
}
}

Categories

Resources