問題:通過在一個ListBox中雙擊,把選中的項添加到另一個ListBox中,但ListBox控件本身並沒有該事件,那么如何實現呢?客戶端腳本javascript可以幫忙。
步驟:1.寫腳本
<script type="text/javascript">
function change(){
var addOption=document.createElement("option");
var index1;
if(document.form1.list_Client.length==0)
return(false);
index1=document.form1.list_Client.selectedIndex;
if(index1<0)
return(false);
addOption.text=document.form1.list_Client.options(index1).text;
addOption.value=document.form1.list_Client.value;
document.form1.list_Client2.add(addOption);
document.form1.list_Client.remove (index1);
}
</script>
2.頁面添加兩個ListBox 以做測試
<body>
<form id="form1" runat="server">
<asp:ListBox ID="list_Client" runat="server" Width="240" Height="300"></asp:ListBox>
>>
<asp:ListBox ID="list_Client2" runat="server" Width="240" Height="300"></asp:ListBox>
</form>
</body>
3.后台頁面加載事件中注冊。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListBoxBand();
list_Client.Attributes.Add("onDblClick", "change()");//雙擊事件
//list_Client.Attributes.Add("onClick", "change()");//單擊事件
}
}
測試結果:
附js操作ListBox方法:
//一次選擇list_Client所有數據導入list_Client2中
function SelectAll(){
var lst1=window.document.getElementById("list_Client");
var length = lst1.options.length;
for(var i=0;i <length;i++) {
var v = lst1.options[i].value;
var t = lst1.options[i].text;
var lst2=window.document.getElementById("list_Client2");
lst2.options[i] = new Option(t,v,true,true);
}
}
//一次選擇刪除list_Client中所有數據
function DelAll(){
var lst=window.document.getElementById("list_Client");
var length = lst.options.length;
for(var i=length;i>0;i--) {
lst.options[i-1].parentNode.removeChild(lst.options[i-1]);
}
}
//選擇一條數據添加到另一個ListBox,步驟詳見上面的例子
function SelectOne(){
var lst1=window.document.getElementById("list_Client");
var lstindex=lst1.selectedIndex;
if(lstindex<0)
return;
var v = lst1.options[lstindex].value;
var t = lst1.options[lstindex].text;
var lst2=window.document.getElementById("list_Client2");
lst2.options[lst2.options.length] = new Option(t,v,true,true);
}
//選擇一條數據刪除
function DelOne(){
var lst=window.document.getElementById("list_Client");
var lstindex=lst.selectedIndex;
if(lstindex>=0) {
var v = lst.options[lstindex].value+";";
lst.options[lstindex].parentNode.removeChild(lst.options[lstindex]);
}
}