Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Am am trying to display the user selected item in a messagebox.

The following command works find.

MessageBox.Show(listBox1.SelectedItem.ToString());

I would like to suppress part of the Selected Item after a blank space by using the Split Command like this:
C#
string test=listBox1.SelectedItem.ToString().Split(' ');
  MessageBox.Show(test[0]);


When attempting to compile this I get the following error message:

Error 1 Cannot implicitly convert type 'string[]' to 'string' C:\WindowsFormsApplication6\WindowsFormsApplication6\Form1.cs 41 25 WindowsFormsApplication6

Is there another property or method I should be using to do this?
Posted
Comments
Richard C Bishop 19-Feb-13 16:07pm    
Your variable "test" is a string and you are using it like an array in the message box. Just do this: MessageBox.Show(test);

Split returns an array which you are trying to set into string test. You almost have it. Combine your two lines of code and do this:

C#
string test=listBox1.SelectedItem.ToString().Split(' ')[0];


This will return the first item in the array as a string.
 
Share this answer
 
C#
string[] test = myListBox.SelectedItem.ToString().Split(new char[] {' '});
if (test.Length > 0)
   MessageBox.Show(test[0]);

or, in some cases,
C#
string[] test = myListBox.SelectedItem.ToString().Split(new char[] {' '}, System.StringSplitOptions.RemoveEmptyEntries);
if (test.Length > 0)
   MessageBox.Show(test[0]);


By the way, pay attention for violation of the naming conventions in listBox1. Auto code generation by designer simply cannot (and should not) do better, but it's your business to rename all auto-generated names to something semantically sensible; never use auto-generated names as is.

—SA
 
Share this answer
 
Comments
Jibesh 19-Feb-13 16:18pm    
+5. Length checking before accessing the array is always advisable.
Sergey Alexandrovich Kryukov 19-Feb-13 16:23pm    
Thank you,
—SA
Sk. Tajbir 19-Feb-13 16:49pm    
nice 5+
Sergey Alexandrovich Kryukov 19-Feb-13 16:59pm    
Thank you,
—SA
Hi,
Split function always return array of string. So use:
C#
string[] test=listBox1.SelectedItem.ToString().Split(' ');


I hope this will help.
Thanks :)
 
Share this answer
 
string test=listBox1.SelectedItem.ToString().Split(' ')[0];

Works Great!

Thank you very much!
 
Share this answer
 
hello,

try

string[] test=listBox1.SelectedItem.ToString().Split(' ');

the Split() method returns an array so your variable needs to be an array.

see here: http://msdn.microsoft.com/en-gb/library/system.string.split.aspx[^]

Valery.
 
Share this answer
 

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