Interaction between two listboxes
Effect:
ASPX page: <Table> <Tbody> <Tr> <TD> <Asp: ListBox id = "lbleft" runat = "server" selectionmode = "multiple"> <Asp: listitem> Add a name </ASP: listitem> <Asp: listitem> Date of Birth </ASP: listitem> </ASP: ListBox> </TD> <TD style = "width: 27px"> <Asp: button id = "btntoright" runat = "server" text = ">" Onclick = "btntoright_click"/> <Br/> <Asp: button id = "btntoleft" runat = "server" text = "<" Onclick = "btntoleft_click"/> </TD> <TD style = "width: 3px"> <Asp: ListBox id = "lbright" runat = "server" Selectionmode = "multiple"> </ASP: ListBox> </TD> </Tr> </Tbody> </Table> <Asp: Label id = "lblmsg" runat = "server"> </ASP: Label>CS code: using system; Using system. Data; Using system. configuration; Using system. collections; Using system. Web; Using system. Web. Security; Using system. Web. UI; Using system. Web. UI. webcontrols; Using system. Web. UI. webcontrols. webparts; Using system. Web. UI. htmlcontrols;
Public partial class test1: system. Web. UI. Page ...{ Protected void page_load (Object sender, eventargs E) ...{
} Protected void btntoright_click (Object sender, eventargs E) ...{ If (lbleft. selecteditem! = NULL) ...{ Additemfromsourcelistbox (lbleft, lbright );
Removeselecteditem (lbleft );
Lblmsg. Text = ""; // Note: Why is this line required?
Foreach (listitem item in lbright. Items) ...{ If (item. Selected) Lblmsg. Text + = item. text; } } }
Protected void btntoleft_click (Object sender, eventargs E) ...{ If (lbright. selecteditem! = NULL) ...{ Additemfromsourcelistbox (lbright, lbleft ); Removeselecteditem (lbright ); } }
Private void removeselecteditem (ListBox listcontrol) ...{ While (listcontrol. selectedindex! =-1) ...{ Listcontrol. Items. removeat (listcontrol. selectedindex ); } }
Private void additemfromsourcelistbox (ListBox sourcebox, ListBox targetbox) ...{ Foreach (listitem item in sourcebox. Items) ...{ If (item. Selected = true &&! Targetbox. Items. Contains (item )) ...{ Targetbox. Items. Add (item ); } } }
}
|