Posted by: Nishant Rana | October 26, 2007

Working with ListBox in .Net Windows Application

Say we want to implement some functionality as shown in the image below in our windows formListBox

Using >> button we want to move values from optional sections to mandatory sections list box and vice versa using << button. But we don’t want the sections which are mandatory to move to optional list box.

Finally we can rearrange items in the Mandatory list box using up and down buttons.

Let’s see the code for all this

Our listboxes are named lstOptional and lstMandatory

>> button is named btnSelect

<< button is named btnDeSelect

When button >>(btnSelect is clicked)

private void btnSelect_Click(object sender, EventArgs e)
{

// if there are no item in lstOptional Listbox return

if (lstOptional.Items.Count == 0)
{

return;
}

// if some item is selected in the lstOptional Listbox check if we already have it in lstMandatory

// if it is there or nothing is selected than return

int g = lstMandatory.FindStringExact(lstOptional.Text);
if(g>-1||lstOptional.Text ==”")
{
return;
}

// finally add that item to lstMandatory, refresh it to make it appear and remove it from lstOptional

lstMandatory.Items.Add(lstOptional.Text );
lstMandatory.Refresh();
lstMandatory.Text = “”;
lstOptional.Items.Remove(lstOptional.Text);
}

When button << DeSelect is clicked

private void btnDeSelect_Click(object sender, EventArgs e)
{

// if nothing is selected in lstMandatory just put the focus over the listbox

if (lstMandatory.Text == “”)
{
lstMandatory.Focus();
return;
}

// checking if the selected item is mandatory on.

// Here we have saved the mandatory items in a hidden listbox on form load

int g = lstHidden.FindStringExact(lstMandatory.Text);
if (g > -1)
{
MessageBox.Show(“This section is mandatory”,”Information”);
}
else
{
lstOptional.Items.Add(lstMandatory.Text);
lstMandatory.Items.Remove(lstMandatory.Text);
}
}

When button Up is clicked we need to move the selected item in upward direction

int selectedItemIndex = lstMandatory .SelectedIndex;
String selectedItemText = lstMandatory .Text;
if (selectedItemIndex != 0)
{
lstMandatory .Items.RemoveAt(selectedItemIndex);
lstMandatory .Items.Insert(selectedItemIndex – 1, selectedItemText);
lstMandatory .SelectedIndex = selectedItemIndex – 1;
}
lstMandatory .Refresh();
lstMandatory .Focus();

Finally when button Down is clicked

int selectedItemIndex = lstMandatory.SelectedIndex;
String selectedItemText = lstMandatory.Text;
int total = lstMandatory.Items.Count;
if (selectedItemIndex < total – 1)
{
lstMandatory.Items.RemoveAt(selectedItemIndex);
lstMandatory.Items.Insert(selectedItemIndex + 1, selectedItemText);
lstMandatory.SelectedIndex = selectedItemIndex + 1;
}
lstMandatory.Refresh();

Bye


Responses

  1. its very hepful to unerstand the concept in deep.
    thanx

  2. its very useful to understand the concept clearly…..
    thanx


Leave a response

Your response:

Categories