前兩天要寫一個操作select的東西,因為急著交貨,隨便寫了一個操作LISTBOX的東西交上去了,
所有事件都是寫在伺服器端,覺得不是很好,今天重寫了一個,是伺服器端和用戶端互動的
前端只有一個資料繫結:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SelectBind();
}
}
protected void SelectBind()
{
for (int i = 0; i < 20; i++)
selectleft.Items.Add(new ListItem("Andy"+(i+1).ToString(),(i+1).ToString()));
}
源:
<body>
<script type="text/javascript" language="javascript">
//交換全部,參數為要交換的對象
function TranAllOption(Obj1,Obj2)
{
if(Obj1.options.length <=0)
{ alert("沒有要移動的項!"); return;}
while(Obj1.options.length >0)
{
Obj2.options.add(new Option(Obj1.options[0].text,Obj1.options[0].value));
Obj1.remove(0);
}
}
//交換部份,參數為要交換的對象
function TranOption(Obj1,Obj2)
{
var show = true;
for(var i=0;i<Obj1.options.length;i++)
{
if(Obj1.options[i].selected == true)
{
Obj2.options.add(new Option(Obj1.options[i].text,Obj1.options[i].value));
Obj1.remove(i);
i=i-1;
show = false;
}
}
if(show)
{
alert("請選擇要移動的項!");
}
}
//上下移動
function SwapOption(obj,index)
{
if(obj.selectedIndex < 0)
{
alert("請選擇要移動的項!");
return;
}
if(index == -1)
{
if (obj.selectedIndex == 0)
{
alert("已經移動到頂了!");
return;
}
else { obj.options(obj.selectedIndex).swapNode(obj.options(obj.selectedIndex-1)); return;}
}
else if(index == 1)
{
if (obj.selectedIndex == obj.options.length-1)
{
alert("已經移動到底了!"); return;
}
else { obj.options(obj.selectedIndex).swapNode(obj.options(obj.selectedIndex+1)); return; }
}
}
</script>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<table>
<tr><td rowspan="4"><select runat="server" multiple="true" id="selectleft" style="border-style:solid; width:200px; height:300px;" ></select></td>
<td><input id="Button1" type="button" value=">> 全部" onclick="TranAllOption(selectleft,selectright)" /></td>
<td rowspan="4"><select runat="server" multiple="true" id="selectright" style="border-style:solid; width:200px; height:300px;" ></select></td>
<td rowspan="2"><input id="Button5" type="button" value="上移" onclick="SwapOption(selectright,-1);" /></td></tr>
<tr><td><input id="Button2" type="button" value="> 增加" onclick="TranOption(selectleft,selectright)" /></td></tr>
<tr><td><input id="Button3" type="button" value="<< 全部" onclick="TranAllOption(selectright,selectleft)" /></td>
<td rowspan="2"><input id="Button6" type="button" value="下移" onclick="SwapOption(selectright,1)" /></td></tr>
<tr><td><input id="Button4" type="button" value="< 增加" onclick="TranOption(selectright,selectleft)" /></td></tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>