In my C# application, I have two ListBox
controls.
One ListBox
, named lstCategory
, is populated with items retrieved from a database.
The other ListBox
is named lstSelCategory
.
I want to move the selected items from lstCategory
into lstSelCategory
, and then sort the items in lstSelCategory
. How might I go about doing this efficiently? Any help would be appreciated.
protected void BtnCopyNext_Click(object sender, EventArgs e)
{
try
{
MakeDecision(lstCategory,lstSelCategory);
}
catch (Exception ex)
{
}
}
private void MakeDecision(ListBox Source, ListBox Target)
{
int[] selectedIndices;
try
{
selectedIndices = Source.GetSelectedIndices();
if (!(selectedIndices.Length == 0))
{
Copy(Source, Target);
}
}
catch (Exception ex)
{
throw ex;
}
}
private void Copy(ListBox Source, ListBox Target)
{
int[] selectedIndices;
ListItemCollection licCollection;
ListBox objTarget;
try
{
selectedIndices = Source.GetSelectedIndices();
licCollection = new ListItemCollection();
objTarget = new ListBox();
if (Target != null && Target.Items.Count > 0)
{
foreach (ListItem item in Target.Items)
{
objTarget.Items.Add(item);
}
Target.Items.Clear();
}
int selectedIndexLength = selectedIndices.Length;
for (int intCount = 0; intCount < selectedIndexLength; intCount++)
{
licCollection.Add(Source.Items[selectedIndices[intCount]]);
}
int collectionCount = licCollection.Count;
for (int intCount = 0; intCount < collectionCount; intCount++)
{
Source.Items.Remove(licCollection[intCount]);
if (!objTarget.Items.Contains(licCollection[intCount]))
objTarget.Items.Add(licCollection[intCount]);
}
Target.DataSource = ConvertToArrayList(objTarget);
Target.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
licCollection = null;
objTarget = null;
}
}
private ArrayList ConvertToArrayList(ListBox Source)
{
ArrayList arrayList;
try
{
arrayList = new ArrayList();
foreach (ListItem item in Source.Items)
arrayList.Add(item.Text);
arrayList.Sort();
}
catch (Exception ex)
{
throw ex;
}
return arrayList;
}