As my previous blog for ComboBox, this is to demonstrate setting and retrieving objects from Listbox, here the difference is to set more than one values in Listbox, and retrieving more than one values from ListBox.
I have a simple class ListValues having two fields with getter and setter function, ListValues class also implemented ToString and Equal functions.
My form having a listBox with name “lstBoxValues” and its property SelectionMode is set to multiple.
There is a lable in form for displaying selected values of listBox and two buttons, one for selecting value in ListBox and another for displaying value of selected items in ListBox.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ListTestApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
lstBoxValues.Items.Add(new ListValue(1, "Value1"));
private void Form1_Load(object sender, EventArgs e)
{
lstBoxValues.Items.Add(new ListValue(1, "Value1"));
lstBoxValues.Items.Add(new ListValue(2, "Value2"));
lstBoxValues.Items.Add(new ListValue(3, "Value3"));
lstBoxValues.Items.Add(new ListValue(4, "Value4"));
lstBoxValues.Items.Add(new ListValue(3, "Value3"));
lstBoxValues.Items.Add(new ListValue(4, "Value4"));
}
private void button1_Click(object sender, EventArgs e)
{
lstBoxValues.ClearSelected();
lstBoxValues.ClearSelected();
ListValue v = new ListValue(3, null);
lstBoxValues.SelectedItems.Add(v);
lstBoxValues.SelectedItems.Add(v);
}
private void button2_Click(object sender, EventArgs e)
{
String values = "";
for (int i = 0; i< lstBoxValues.SelectedItems.Count; i++)
for (int i = 0; i< lstBoxValues.SelectedItems.Count; i++)
{
values += lstBoxValues.SelectedItems[i] as ListValue;
values += ", ";
values += lstBoxValues.SelectedItems[i] as ListValue;
values += ", ";
}
lblValue.Text = values;
lblValue.Text = values;
}
}
}