ASP.NET 2 CHECKLISTBOX SELECTED INDEX CHANGED - Developers Anonymous
Wednesday, February 08, 2006 8:46 AM Trivium DawnWalker

ASP.NET 2 CHECKLISTBOX SELECTED INDEX CHANGED

Man did I battle with this!

Thank goodness I've got a great boss who taught some things I didn't know about HTML to help me out.

Basically, I wanted add/remove items to an arrayList when selected. Adding wasn't a problem at all. Removing on the other-hand. I'm pretty new to VS2005 and common sense says that functionality for controls should stay the same. Not anymore!!!!

If I uncheck something then chkList.SelectedIndex.Selected should return false. BUT it was always returning true, because it was automatically moving the seleted index to the index of an item that was selected.

So, to get the currently selectedIndex you need to fetch the __EventTarget of that Postback. This is done by accessing the Request.Form[0] or Request.Form["__EVENTTARGET"] object. This tells the page what object was selected. It returns the following value:

chklstSelect$7

chklstSelect is the ID of the CheckListBox object and the $ is the separator. The 7 is the Index that was selected. Then just declare a string and fill it with the :
Request.Form[0].ToString();

THEN remove all the characters up to and including the $ sign:

vSelectedIndex = vSelectedIndex.Remove(0, vSelectedIndex.LastIndexOf("$") + 1);

then convert the string to an Interger:

int vIndex = Int32.Parse(vSelectedIndex);

Now that we have the Index we set the current SelectIndex for the CheckListBox as follows and check whther the object selected. If it isn't then removed those values from my two ArrayLists.:

//Select that Item via its index and check its current property
if (!(chklstSelect.Items[vIndex].Selected))
{
    //Remove entry from the array
    vDescArray.Remove(chklstSelect.Items[vIndex].Text);
    vIDArray.Remove(chklstSelect.Items[vIndex].Value);    
}

Glad thats finally over. I hope this helps someone else as googling this topic did NOTHING for me!
Filed under:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: