1

I have listbox1 - its datasource is a column (productname).

so i have in the listbox a MultiSelection option.

and im trying to make a MessageBox for all the option i selected and this the code:

  foreach (object selectedItem in listBox1.SelectedItems)
  {
       MessageBox.Show((selectedItem.ToString() + Environment.NewLine));
   }

the problem is that im getting this value insteadSystem.Data.DataRowView

Ofiris
  • 6,047
  • 6
  • 35
  • 58
Shmulik Cohen
  • 115
  • 2
  • 3
  • 7

3 Answers3

5

How do you populate the listbox (ie what is exactly the datasource)?

From your comment I would say a DataView (and wich contains DataRowView...)

So you just need to cast the SelectedItem into DataRowView in order to get a value from this DataRowView:

foreach (object selectedItem in listBox1.SelectedItems)
{
     DataRowView dr = (DataRowView)selectedItem;
     String result = dr["productname"].ToString;
     MessageBox.Show(result + Environment.NewLine);
}

The VB.Net developers that could fall on this post could also be interested in this.

Community
  • 1
  • 1
Chris
  • 8,527
  • 10
  • 34
  • 51
  • im getting this error : 'System.Data.DataRowView' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Data.DataRowView' could be found (are you missing a using directive or an assembly reference?)" – Shmulik Cohen May 27 '13 at 18:25
  • See updated answer, it was a problem of VB C# conversion http://stackoverflow.com/q/7873972/2387010 – Chris May 27 '13 at 18:55
-1

Try to change with this

ListBoxItem lbi ;
String myStr ;

for (int i =0; i <= listbox1.selecteditems.count-1 ; i++)
    {
        lbi = (ListBoxItem)(listBox1.ItemContainerGenerator.ContainerFromIndex(i)); 
        myStr += lbi + Environment.NewLine);            
    }

 MessageBox.Show(myStr);
matzone
  • 5,703
  • 3
  • 17
  • 20
-1

You can also use the ordinal value as in:

 DataRowView dr = (DataRowView)selectedItem;
 String result = dr[1].ToString;
MC9000
  • 2,076
  • 7
  • 45
  • 80