I think what you want is to sort the listbox
items by putting them into an Array
, but at the same time, you also have changed the listbox
items into array of string
and string
cannot be sorted by descending/ascending as int
does
In that case, you should rather get your listbox
items as Array
of int
and then sort it as int
before displaying it in your Label
as string
int[] dizi = new int[listBox1.Items.Count]; //here is int array instead of string array, put generic size, just as many as the listBox1.Items.Count will do
for (int i = 0; i < listBox1.Items.Count; i++) {
dizi[i] = Convert.ToInt32(listBox1.Items[i].ToString());
//assuming all your listBox1.Items is in the right format, the above code shall work smoothly,
//but if not, use TryParse version below:
// int listBoxIntValue = 0;
// bool isInt = int.TryParse(listBox1.Items[i].ToString(), out listBoxIntValue); //Try to parse the listBox1 item
// if(isInt) //if the parse is successful
// dizi[i] = listBoxIntValue; //take it as array of integer element, rather than string element. Best is to use List though
//here, I put the safe-guard version by TryParse, just in case the listBox item is not necessarily valid number.
//But provided all your listBox item is in the right format, you could easily use Convert.ToInt32(listBox1.Items[i].ToString()) instead
}
Array.Sort(dizi); //sort array of integer
label2.Text = dizi[0].ToString(); //this should work
This way, dizi
would be a sorted version of you listbox1
items as int
. Whenever you need this as string
just use ToString()
for the array element
Also, as a side note: consider of using List
of int
and int.TryParse
to get the integer element value from the listBox.Items
in case you are not sure if all the listBox.Items
can be converted to int
for one reason or another.
solved Cannot implicitly convert type ‘int’ to ‘string’ .I can’t [closed]