Click here to Skip to main content
15,888,085 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I have a listbox of numbers. When I click on the number I want to show it in the console. Is there any reason why this wouldn't work.

Console.WriteLine(Int32.Parse(listBox1.SelectedItems.ToString()));

Any help is appreciated.
Posted
Updated 14-Oct-10 6:51am
v3

1) If you need to display the number, then you dont need to parse to int as Console.WriteLine() will again parse to string.

2) SelectedItems - you are converting not one but one or more number selected by the user. This cannot be done in a single parse statement. You need to convert all selected numbers one by one.
 
Share this answer
 
v2
Why are you trying to convert a string to an int just so you can reconvert it to a string to write it on the console?

You may also note here[^] that SelectedItems returns a collection and not a single string.
 
Share this answer
 
Comments
Neil Cross 14-Oct-10 17:32pm    
I am trying to get the number for a different purpose, the code I provided was only an example of the parse method not working. I appreciate your help though, it seems a bit obvious now I know what the problem is.
Abhinav is right...which is why I marked his answer as a 5, but I wanted to elaborate a bit more on what he said and provide (hopefully) some helpful tips for the future.

When you get an error like this, the best thing to do is go through your code step by step in the debugger. If you are using Visual Studio, use your Watch window. If something doesn't work the way you expected, put each of the variables into the watch window and see the results.

In your case, if you had done this, you could have started by putting listBox1.SelectedItems.ToString() in the watch window. If you had done that, you would have seen that it equaled something like:

System.Windows.Forms.ListBox+SelectedObjectCollection


That's probably not what you were expecting. Then, when you used the Parse function, it would have thrown an error because it is not a numeric value.

My other suggestion is only use the Parse methods if you are assured that it will work. Otherwise, use TryParse instead.
 
Share this answer
 
Comments
Neil Cross 14-Oct-10 17:33pm    
Thanks for your help, I appreciate it.
Abhinav S 14-Oct-10 23:27pm    
Good comments.
Console.WriteLine();Takes String i think if u write like this it will work
Console.WriteLine(listBox1.SelectedItems.ToString());
 
Share this answer
 
Comments
William Winner 14-Oct-10 14:09pm    
no it won't. listBox1.SelectedItems.ToString() = "System.Windows.Forms.ListBox+SelectedObjectCollection"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900