Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

MultiSelect ListBox
By Arulraja Livingston

This article shows how to get the SelectedItems from the ListBox for the multiple selected items.

We can fill the ListBox using a DataSet or ArrayList or we can simple add the items to the items collection.If we simply add the items to the items collection, it's very easy to get the selecteditems. but if we use datasource property to fill the Listbox we will have some problems getting the multiple selected items

Here is the samples for how to get the multipleselected items if we use the dataset or ArrayList to fill the ListBox.

Using ArrayList:
----------------
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Sample
{
  private void Form1_Load(object sender, System.EventArgs e)
  {
    IList m_arr = new ArrayList();
    m_arr.Add(new Names(1,"Test1"));
    m_arr.Add(new Names(2,"Test2"));
    m_arr.Add(new Names(3,"Test3"));
  }
  private void button1_Click(object sender, System.EventArgs e)
  {   
    for(int cnt =0;cnt <= listBox1.SelectedItems.Count -1;cnt++)
    {
      Names my_name;
      my_name = listBox1.SelectedItems[cnt] as Names;
      MessageBox.Show(my_name.ID.ToString()); 
      MessageBox.Show(my_name.Name);
                         
    }
  }
}
public class Names
{
  public  Names(int id, string name){
    m_id = id;
    m_name = name;
  }
  private int m_id;
  private string m_name;
  public int ID
  {
    get{return m_id;}
    set{m_id = value;}
  }
  public string Name
  {
    get{return m_name;}
    set{m_name = value;}
  }

}

Using DataSet:
--------------
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Sample
{
  private void Form1_Load(object sender, System.EventArgs e)
  {
    DataSet ds = new DataSet();
    ds.ReadXml(@"c:\Livingston.xml");
    listBox1.DataSource = ds.Tables["Table"];
    listBox1.DisplayMember = "NAME";
    listBox1.ValueMember = "ID"; 
  }
  private void button1_Click(object sender, System.EventArgs e)
  {    
    for(int cnt =0;cnt <= listBox1.SelectedItems.Count -1;cnt++)
    {
      DataRowView  ln = listBox1.SelectedItems[cnt]as DataRowView;
      MessageBox.Show(ln["ID"].ToString());
      MessageBox.Show(ln["Name"].ToString());           
    }
  }

}