We all would have encountered the situation below where we are asked to select few items from a list of items. The selected items are transfered to another listbox by clicking a simple button. I have put a sample screen shot of that below.
Create a new ASP.NET website in VS2010. Visual Studio will automatically add a default.aspx page which has a master page to it. Lets add the Listbox controls to the page. I’ll put the Listboxes and buttons in a table tag so that the output is better..
The code is as shown:
Coming to the code,
You can see that I have added a label, two ListBoxes and two buttons, one to add items, other to remove the items. The first listbox is populated with static data (You can also load data into it dynamically from Database). The second ListBox is initially empty.
The function takes two parameters:
- the source listbox ID
- the target listbox ID
I have put comments in the code so that it is understood easily. Basically what is happening in the function is the selected items in the source listbox are taken. New “Option” is created for the target listbox and the items are added into the target listbox. Also, the selected items are removed from the source listbox.
You can observe the following line in the OnClientClick attribute for the Add button:
If you get a doubt as to why I have put “MainContent_” before the IDs of the source listbox and the Target listbox, the reason is, our Default.aspx is placed inside a content place holder. Remember I mentioned that default.aspx has a master page to it earlier in this post?
So when a page placed in a content place holder is rendered, the IDs of all the controls in the page are Prefixed with the ID of the ContentPlaceHolder in which the page is placed. (“MainContent” in this example).
You are not done with this. You also have to add the HTML “onclick” attribute to the buttons in order to make it work. Add the below lines in the Page_Load function of Default.aspx.
btnAddItem.Attributes.Add(“onclick”, “return selectItems(‘” + lstboxItems.ClientID + “‘, ‘” + lstboxSelectedItems.ClientID + “‘);”);
btnRemoveItem.Attributes.Add(“onclick”, “return selectItems(‘” + lstboxSelectedItems.ClientID + “‘, ‘” + lstboxItems.ClientID + “‘);”);
Now save, build and run the application. You can move the items among the list boxes.
Hope this helps! 🙂