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
}
}
}
Related
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 6 years ago.
When I press the click event to add array values, it gives me an out of index exception error. I'd like to know why it's happening and how to fix it, thanks.
using System;
using System.Windows.Forms;
namespace ArrayTestCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double total = 0;
double average = 0;
double scoreInput = 0;
int countOfExams = 0;
double[] examScores;
double count = 0;
//field array declare
private void enterBtn_Click(object sender, EventArgs e)
{
countOfExams = int.Parse(numOfExamsTextBox.Text);
examScores = new double[countOfExams];
examLabel.Text = "Exam 1: ";
label1.Visible = false;
numOfExamsTextBox.Visible = false;
enterBtn.Visible = false;
examLabel.Visible = true;
examScoresTextBox.Visible = true;
addBtn.Visible = true;
}
private void addBtn_Click(object sender, EventArgs e)
{
examLabel.Text = "Exam " + (countOfExams +1) + ":";
examScores[countOfExams] = double.Parse(examScoresTextBox.Text);
countOfExams++;
examScoresTextBox.ResetText();
examScoresTextBox.Focus();
if(countOfExams >= examScores.Length)
{
MessageBox.Show("hoise vaya");
}
}
private void clearBtn_Click(object sender, EventArgs e)
{
Array.Clear(examScores, 0, examScores.Length);
ClearAll();
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
public void ClearAll()
{
examLabel.Text = "Exam:";
examScoresTextBox.ResetText();
numOfExamsTextBox.ResetText();
}
private void calcBtn_Click(object sender, EventArgs e)
{
}
}
}
In the first line of your enterBtn_Click,
countOfExams = int.Parse(numOfExamsTextBox.Text);
I suppose you are using countOfExams as the total length of the array.
Later in the second line of your addBtn_Click,
examScores[countOfExams] = double.Parse(examScoresTextBox.Text);
countOfExams++;
I suppose you are using countOfExams to track the actual number of exams. Because countOfExams is already set to the length, it results in OutOfRangeException.
Thus, I suggest you to use another variable (e.g. a local variable) for the total length of the array,
var size = int.Parse(numOfExamsTextBox.Text);
examScores = new double[size];
double[] examScores; has been defined as array, which was never initialized if you are not calling enterBtn_Click first
Ideally,
You should first initialize/ check if it is initialized it by
double[] examScores = new double[<length>];
also, the counter starts from 0 and not 1
If you are not sure about the length or capacity, use List
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!
I am currently doing a simili-HangMan project. As I looked through many other projects up here, I haven't found what I was looking for exactly.
Notes:
* The variable motRechercher is the randomized word.
* It can be used everywhere - I did a get set for it.
MY QUESTION IS: I want to display a string in a textbox that is a random word selected from a list, how do I do that?
Here's my code for the textbox:
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
for (int i = 0; i <= motRechercher.Length; i++)
{
StringBuilder sb = new StringBuilder(motRechercher);
sb[i] = '_';
string sba = sb.ToString();
txtMot.Text=sba;
}
}
If the word is for an example : Cat. It should display: _ _ _
Here's my code for the random word selector (It works) - It's mostly to give an idea:
private void btnDemarrer_Click(object sender, RoutedEventArgs e)
{
Random rdn = new Random();
int nbreAleatoire = rdn.Next(0, 27);
motRechercher = lesMots[nbreAleatoire];
}
If you have any questions regarding my code I'll edit it to make it easier for you to understand/help me.
instead of
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
for (int i = 0; i <= motRechercher.Length; i++)
{
StringBuilder sb = new StringBuilder(motRechercher);
sb[i] = '_';
string sba = sb.ToString();
txtMot.Text=sba;
}
}
add another button for next random no to populate to text box.
inside button click do this which will check the length and get the data for you:
private void btnNext_Click(object sender, RoutedEventArgs e)
{
if(motRechercher.Length > 0)
{
String str = new String('_', motRechercher.Length);
txtMot.Text = str;
}
}
If I understand the question, this might be what you're after:
bool changing = false; // variable in class-scope
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
if (changing == false)
{
try
{
changing = true;
String str = new String('_', motRechercher.Length);
txtMot.Text = str;
}
finally
{
changing = false;
}
}
}
The thing I want to do is that i want to select 1,2 or 3 items from the listbox and save them into a session and then display them all on another form in a listbox.
Here's my code!
This is my first post on stack overflow, so no hate please <3
//WebForm1
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lstProducts.Items.Add("Soap");
lstProducts.Items.Add("Schampoo");
lstProducts.Items.Add("Conditioner");
}
}
protected void cmdBuy_Click(object sender, EventArgs e)
{
string[] products = new string[3];
for (int i = 0; i < lstProducts.Items.Count; ++i)
{
if (lstProducts.Items[i].Selected)
products[i] = lstProducts.Items[i].Text;
else
products[i] = "0";
}
Session["Cart"] = products;
}
protected void cmdCart_Click(object sender, EventArgs e)
{
if (Session["Cart"] != null)
{
Response.Redirect("WebForm2.aspx");
}
}
}
//WebForm2
protected void Page_Load(object sender, EventArgs e)
{
string[] products = (string[])Session["Cart"];
for (int i = 0; i < 3; ++i)
{
if (products[i] != "0")
{
lstCart.Items.Add(products[i]);
}
}
}
}
}
The thing is that I only get the last selected item to display in the listbox on form2???
Try this
To store all items of the of the list box, you can add that items in array as:
string[] a = new string[]{"item 1","item 2","item 3"};
Session["values"] = a;
And in the next page, you can retrieve it like this.
string[] a = (string[])Session["values"]
EDIT #1
your case you can do like
ArrayList al = new ArrayList();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected == true)
{
al.Add(ListBox1.Items[i].Value);
}
}
Session["selectedValues"] = al;
now you can use this sessiom variable in another page, but don't forget to cast in ArrayList type of object.
Hi People I'm newbie in the C# world and I'm having a problem. I have done an array in the Form_Load method of my program, but I need to access the array in a picture_box method like this:
private void Form2_Load(object sender, EventArgs e)
{
//In this method we get a random array to set the images
int[] imgArray = new int[20];
Random aleatorio = new Random();
int num, contador = 0;
num = aleatorio.Next(1, 21);
imgArray[contador] = num;
contador++;
while (contador < 20)
{
num = aleatorio.Next(1, 21);
for (int i = 0; i <= contador; i++)
{
if (num == imgArray[i])
{
i = contador;
}
else
{
if (i + 1 == contador)
{
imgArray[contador] = num;
contador++;
i = contador;
}
}
}
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(#"C:\Users\UserName\Desktop\MyMemoryGame\" + imgArray[0] + ".jpg");
}
But I only get the error: Error 1 The name 'imgArray' does not exist in the current context
You need to define int[] imgArray at the class level (outside of Form2_Load) rather than inside it. Otherwise the "scope" of that variable is limited to that function. You will need to knock off the first "int[]" part in Form2_Load to prevent you from just declaring a new variable.
For example:
public class MyClass
{
private int[] myInt;
public void Form2_Load(...) {
myInt = ...;
}
}
The error means exactly what it says.
You've declared the array in the scope of the Form2_Load function. Outside of it, it will not exist.
To do what you're trying to achieve, add a private array to the form itself.
private int[] _imgArray = new int[20];
private void Form2_Load(object sender, EventArgs e)
{
//Setup the imgArray
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//_imgArray is now available as its scope is to the class, not just the Form2_Load method
}
Hopefully that helps.