It's my first post.
I'm trying to make multiple sums in a checkedlistbox in Visual C#. There are 108 numbers, one in each row, and I'm trying to sum the checked item(s) with each one of the rest and print it in a textbox.
I have done this, but I think it's incorrect.
This actually does the sum, but also with the number itself and the whole thing 108 times
I want to add the checked number with the rest numbers in the checkbox.
private void button2_Click(object sender, EventArgs e)
{
foreach(string checkednumber in checkedlistbox1.CheckedItems)
{
double x = Convert.ToDouble(checkednumber);
double a = 0;
for (double y = 0; y < checkedlistbox1.Items.Count; ++y)
{
foreach (string othernumbers in checkedlistbox1.Items)
{
double z = Convert.ToDouble(othernumbers);
sum = x + z;
string str = Convert.ToString(sum);
listbox1.Items.Add(str);
}
}
}
}
Thanks for any help.
You just want to sum the numbers for items that are checked?
double sum = 0;
foreach(object checkedItem in checkedlistbox1.CheckedItems)
{
try
{
sum += Convert.ToDouble(checkedItem.ToString());
}
catch (FormatException e) {} //catch exception where checkedItem is not a number
listbox1.Items.Add(sum.ToString());
}
Your question is incredibly unclear, I'm not really sure if this is what you want at all.
Also you can use linq to achieve it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var result = from num in this.checkedListBox1.CheckedItems.OfType<string>()
select Convert.ToInt32(num);
this.textBox1.Text = result.Sum().ToString();
}
}
}
Related
Hi guys every time I pressed the button to generate the sorted string the output gets concatenated in the previous label output. I'm lost on how to clear the previous output on the label before showing the new one here's my 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 You_Source
{
public partial class Form1 : Form
{
string method;
public Form1()
{
InitializeComponent();
}
private void radio_checked(object sender, EventArgs e)
{
RadioButton radio = (RadioButton)sender;
method = radio.Text;
//label_Output.Text = method;
}
private void button_Sort_Click(object sender, EventArgs e)
{
string input = textBox_Input.Text;
label_Output.Clear();
if ( method == "Bubble Sort")
{
char[] charInput = input.ToCharArray();
char temp;
for (int j = 0; j <= charInput.Length - 2; j++)
{
for (int i = 0; i <= charInput.Length - 2; i++)
{
if (charInput[i] > charInput[i + 1])
{
temp = charInput[i + 1];
charInput[i + 1] = charInput[i];
charInput[i] = temp;
}
}
}
foreach (char letter in charInput)
label_Output.Text = label_Output.Text+letter;
}
}
}
can anyone give me a hint on what to do.
example( if i enter "cba" the output would be "abc", then when i entered another input in the text box "zyx" the new label output would be "abcxyz". I just one the new one "xyz" to be shown.
You can just set the string to "" at some point of your code, and overwrite it with the new string
I am aware of the question asked by user ElPeta. However the selected answer to his question does not fix my issue.
In my program I have a list box, whenever a check box is clicked and its checked property set to true, the list box is populated with text, however when the check box is unchecked, I want to remove the text associated with the check box from the list box.
Example Before and After:
My Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CarFinderByMake
{
public partial class frmCFBM : Form
{
public frmCFBM()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'honestRalphsUsedCarsDataSet.tblCars' table. You can move, or remove it, as needed.
this.tblCarsTableAdapter.Fill(this.honestRalphsUsedCarsDataSet.tblCars);
}
private void chkFord_CheckedChanged(object sender, EventArgs e)
{
if (chkFord.Checked)
{
//lstCarMakes.Items.Clear();
//populating the listbox
var fordCars = from x in honestRalphsUsedCarsDataSet.tblCars where x.Make.StartsWith("Ford") select x;
foreach (var x in fordCars)
{
lstCarMakes.Items.Add(x.ModelYear + " " + x.Make + " - " + x.Color);
}
}
else
{
for (int x = 0; x <= lstCarMakes.Items.Count; ++x )
{
//here I was attempting to find the index of the items...
if (lstCarMakes.Items.Contains("Ford"))
{
lstCarMakes.Items.IndexOf("Ford");
//and after that I was going to remove the items.
}
}
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
//lstCarMakes.Items.Clear();
//populating the list box
var cadillacCars = from x in honestRalphsUsedCarsDataSet.tblCars where x.Make.StartsWith("Cadillac") select x;
foreach (var x in cadillacCars)
{
lstCarMakes.Items.Add(x.ModelYear + " " + x.Make + " - " + x.Color);
}
}
}
}
}
The ListBox.ObjectCollection returned from ListBox.Items has methods Remove(obj) and RemoveAt(index). You can loop it backwards and use RemoveAt:
private void chkFord_CheckedChanged(object sender, EventArgs e)
{
if (chkFord.Checked)
{
// you have it working ...
}
else
{
for (int x = lstCarMakes.Items.Count - 1; x >= 0; x-- )
{
string car = lstCarMakes.Items[x].ToString();
if(car.IndexOf("Ford", StringComparison.InvariantCultureIgnoreCase) >= 0)
lstCarMakes.Items.RemoveAt(x);
}
}
}
I have also used String.IndexOf instead of Contains to support case-insensitivity.
I don't know your specific error, but I imagine you might have an issue since you're using the item count of the listbox, and removing the items. When the item gets deleted the item count is changed. I believe there's a method for list box such as listbox.BeginUpdate() you can call before making changes to the items within the listbox and listbox.Update() after you're finished. Let me know if I'm in the right area with your problem
The assignment is as follows:
Total Sales
Use the attached file named Sales.txt. Create an application that
reads the file’s content into an array of double or decimal
displays the array’s content in a ListBox control,
calculates the total of the array’s values, average sales, largest sales, smallest sales
Display the Total Sales, Average sales, Highest Sales and Smallest Sales
Form should look similar to the following:
How do I get the data to display the Total/Average/High/Low Sales part of the image to display properly by typing the corresponding code?
I'd like to do this on my own so if you could provide an example that might relate to what I am doing that would really help.
Here's what I've been able to type up so far:
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;
using System.IO;
namespace Total_Sales
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void displayButton_Click(object sender, EventArgs e)
{
//declaring array
const int SIZE = 100;
decimal[] sales = new decimal[SIZE];
//varible to hold amount stored in array
int count = 0;
decimal additionHolder = 0;
//declaring streamreader
StreamReader inputFile;
//opening the sales file
inputFile = File.OpenText("../../Sales.txt");
try
{
//pull contents from file into array while there is still items
//to pull and the array isnt full
while (!inputFile.EndOfStream && count < sales.Length)
{
sales[count] = decimal.Parse(inputFile.ReadLine());
count++;
}
//close the file
inputFile.Close();
//display contents in listbox
for (int index = 0; index < count; index++)
{
ListBox.Items.Add(sales[index]);
}
//add all the values
for (int index = 0; index < sales.Length; index++)
{
additionHolder += sales[index];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Here are two solutions. The first using an array, the second using a List. In both example's I presume that the textboxes for total, average, min and max sales are called TotalSales, AverageSales, MinSales and MaxSales.
private void displayButton_Click(object sender, EventArgs e)
{
const int SIZE = 100;
decimal[] sales = new decimal[SIZE];
int count = 0;
decimal totalSales, averageSales, minSales, maxSales;
StreamReader inputFile;
inputFile = File.OpenText("../../Sales.txt");
try
{
while (!inputFile.EndOfStream && count < sales.Length)
{
sales[count] = decimal.Parse(inputFile.ReadLine());
minSales = count == 0 ? sales[count] : Math.Min(minSales, sales[count]);
maxSales = count == 0 ? sales[count] : Math.Max(maxSales, sales[count]);
totalSales += sales[count];
ListBox.Items.Add(sales[count]);
count++;
}
inputFile.Close();
averageSales = totalSales / sales.Length;
TotalSales.Text = totalSales;
AverageSales.Text = averageSale;
MinSales.Text = minSales;
MaxSales.Text = maxSales;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Using a List and Linq:
private void displayButton_Click(object sender, EventArgs e)
{
List<decimal> sales = new List<decimal>(); // notice: no size limitation
StreamReader inputFile;
inputFile = File.OpenText("../../Sales.txt");
try
{
while (!inputFile.EndOfStream)
{
var sale = decimal.Parse(inputFile.ReadLine());
sales.Add(sale);
ListBox.Items.Add(sale);
}
inputFile.Close();
TotalSales.Text = sales.Sum();
AverageSales.Text = sales.Average();
MinSales.Text = sales.Min();
MaxSales.Text = sales.Max();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As you can see this code is much more concise.
BTW, I wrote this code without Visual Studio at hand so it might contain some typo's.
After you read values from file just use Linq methods and set Text property of yours TextBox controls.
var total = sales.Sum();
var avg = sales.Average();
var min = sales.Min();
var max = sales.Max();
totalTextBox.Text = total.ToString(); //example for TextBox named totalTextBox
remember to add using :)
using System.Linq;
I'm just starting out and learning how to code in C Sharp. We have a class project where we need to make a program that is a guessing game of a random number between 1 and 100. I have that working (currently for testing I'm only doing 1-10), but I wanted to go a step past the basic code and add in a few touches of my own. I have four labels, two with words to describe what they are for, and two that I want the data in to change. Say you're guessing between 1 and 100, and you guess 25 and its to low and its the highest number you've guessed that is to low, I want that displayed, same if you guess a number like 70 and its to high I want that displayed in the label. It seems easy enough but I'm not having any luck with it. Being new to coding I'm going to post my whole code as I'm not sure where the error is. Please note since the code is not working, I only have it set up for the low number until I figure it out.
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 WindowsFormsApplication1
{
public partial class frmMain : Form
{
Double count = 0;
int randomNumber;
Random rand = new Random();
public frmMain()
{
InitializeComponent();
randomNumber = rand.Next(10) + 1;
lblLowShow.Text = "0";
lblHighShow.Text = "100";
}
private void btnGuess_Click(object sender, EventArgs e)
{
count++;
int guessedNumber;
guessedNumber = int.Parse(txtEnterGuess.Text);
if (guessedNumber > randomNumber)
{
MessageBox.Show("To High! Please try again");
}
if (guessedNumber < randomNumber)
{
int lowguess;
MessageBox.Show("To Low! Please try again");
lowguess = Convert.ToInt32(lblLowShow);
if (guessedNumber < lowguess) // Changes the number of the highest, low guess that is displayed.
{
string LowShow;
LowShow = lowguess.ToString();
lblLowShow.Text = LowShow;
}
}
else
{
MessageBox.Show("Congratulations! You won in " + count + " tries!");
count = 0;
randomNumber = rand.Next(10) + 1;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnNewGame_Click(object sender, EventArgs e)
{
}
}
}
Visual studio isn't doing any of the red dots to show an error in the code, so that's not helping me track down the mistake(s).
You are missing a simple else statment before the condition of if the guessed number is lower then the desired number. That's why the computer goes directly to the next if statment and prints a message that the user won the game.
just this:
else//
if (guessedNumber < randomNumber)
{
int lowguess;
MessageBox.Show("To Low! Please try again");
lowguess = Convert.ToInt32(lblLowShow);
if (guessedNumber < lowguess) // Changes the number of the highest, low guess that is displayed.
{
string LowShow;
LowShow = lowguess.ToString();
lblLowShow.Text = LowShow;
}
}
My app is to test for prime number. First time I enter a prime number, the result is true and number is displayed to user. But second time, the prime number check is not functioning as expected. Here is my code:
private void button1_Click(object sender, EventArgs e)
{
label3.Text = textBox1.Text;
float a = (float)Convert.ToDouble(textBox1.Text);
if (check_Number(ref a) == true)
{
ResultCheck.Text = "Input Number is Prime";
}
else if (check_Number(ref a) == false)
{
ResultCheck.Text = "Input Number is not Prime";
}
}
here is an example program that uses trial division.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PrimeCheck
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = textBox1.Text;
double testthis = 0;
if (double.TryParse(textBox1.Text, out testthis))
{
if (CheckForPrime(testthis))
{
MessageBox.Show("prime time!!");
}
}
}
bool CheckForPrime(double number)
{//there are better ways but this is cheap and easy for an example
bool result = true;//assume we are prime until we can prove otherwise
for (double d = 2; d < number; d++)
{
if (number % d == 0)
{
result = false;
break;
}
}
return result;
}
}
}