Within my system in C# I have a list box that the user can add up to 30 integers into. I have also added 5 different labels, these being: maximum entries allowed:, first value:, middle value:, last value:, and Count:, count being the total amount of integers that are in the list box. I am looking to see how to code these labels so that the values are displayed in each label. Can anyone help? This is the code that I have for the 'Add integer to list box'.
int acceptedNum = 0;
if (txtInsert.Text != "")
{
if (lstIntegers.Items.Contains(txtInsert.Text))
{
if (!(int.TryParse(txtInsert.Text, out acceptedNum) && acceptedNum < 0 || acceptedNum >= 100))
{
lstIntegers.Items.Add(txtInsert.Text);
txtInsert.Clear();
txtInsert.Focus();
bubbleSort();
}
else
{
MessageBox.Show("Please input value between 1-100", "error", MessageBoxButtons.OK);
txtInsert.Text = "";
}
}
else
{
MessageBox.Show("Number already exists in list", "error", MessageBoxButtons.OK);
}
}
else
{
MessageBox.Show("Please input value between 1-100", "error", MessageBoxButtons.OK);
}
if (lstIntegers.Items.Count == 30)
{
MessageBox.Show("Maximum number of entries exceeded", "error", MessageBoxButtons.OK);
//button enabled was false however couldn't then add another
btnInsert.Enabled = true;
}
}
You can use List.Sort
to get the correct sort, no need for the bubbleSort
method. You can use Enumerable.First
, Last
and simple math to get the first,last and middle values:
int acceptedNum;
bool validNumber = int.TryParse(txtInsert.Text, out acceptedNum);
if (!validNumber || acceptedNum < 1 || acceptedNum > 100)
{
MessageBox.Show("Please input value between 1-100", "error", MessageBoxButtons.OK);
return;
}
List<int> existingNumbers = lstIntegers.Items.Cast<Object>().Select(System.Convert.ToInt32).ToList();
if (existingNumbers.Contains(acceptedNum))
{
MessageBox.Show("Number already exists in list", "error", MessageBoxButtons.OK);
return;
}
existingNumbers.Add(acceptedNum);
existingNumbers.Sort(); // Quicksort with 30 items
int firstValue = existingNumbers.First();
int lastValue = existingNumbers.Last();
int middleValue = existingNumbers[existingNumbers.Count / 2];
int count = lstIntegers.Items.Count;
int maxNumbers = 30;
if (count == maxNumbers)
{
MessageBox.Show("Maximum number of entries exceeded", "error", MessageBoxButtons.OK);
btnInsert.Enabled = false;
}
lstIntegers.Items.Clear();
lstIntegers.Items.AddRange(existingNumbers.Cast<object>().ToArray());
I've shown you also how to prevent "spaghetticode" by inversing the conditions and returning early.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.