我在用dotnet做一個項目的過程中,遇到了一個listbox的問題:通過在一個listbox中雙擊,把選中的項添加到另一個listbox中,但listbox控件本身并沒有該事件,那么如何實現呢?我就想到了客戶端腳本javascrit,通過查閱相關資料,終于把這個問題解決了,現在寫出來與大家分享,希望能對大家有所幫助。
這里有三個問題:
第一:雙擊所要執行的javascript代碼是什么?
注意:javascript代碼的語法要正確,即每一行都要以“;”結尾;
function change()
{
var addoption=document.createelement("option");
var index1;
if(document.form1.listbox1.length==0)return(false);
index1=document.form1.listbox1.selectedindex;
if(index1<0)return(false);
addoption.text=document.form1.listbox1.options(index1).text;
addoption.value=document.form1.listbox1.value;
document.form1.listbox2.add(addoption);
document.form1.listbox1.remove (index1);
}
第二:如何將 javascript 代碼轉換為c#代碼?
public static void listbox_dblclick(page page,system.web.ui.webcontrols.webcontrol webcontrol,string sourcecontrolname,string targetcontrolname)
{
sourcecontrolname = "document.form1." + sourcecontrolname;
targetcontrolname = "document.form1." + targetcontrolname;
string js = "<script language=javascript> function change(sourcecontrolname,targetcontrolname)";
js += "{";
js += "var addoption=document.createelement( option ); /n";
js += " var index1; /n";
js += "if(sourcecontrolname.length==0)return(false);/n";
js += " index1=sourcecontrolname.selectedindex; /n ";
js += " if(index1<0)return(false);/n";
js += " addoption.text=sourcecontrolname.options(index1).text; /n";
js += "addoption.value=sourcecontrolname.value; /n";
js += "targetcontrolname.add(addoption); /n";
js += "sourcecontrolname.remove (index1) /n"; js +="}";
js += "</script>";
//注冊該 javascript ;
page.registerstartupscript("",js);
//為控件添加雙擊事件;
webcontrol.attributes.add("ondblclick","change(" + sourcecontrolname + "," + targetcontrolname + ");");
}
在該方法中,sourcecontrolname是要綁定雙擊事件的控件,targetcontrolname是接收雙擊事件選定項的控件。
這里有一個問題,如何讓對象作為參數傳給javascript的change函數,我這里采用的是用 sourcecontrolname ,targetcontrolname 來傳遞兩個listbox的name, 然后與“document.form1.“組合成一個串來傳遞給javascript的change函數,即
sourcecontrolname = "document.form1." + sourcecontrolname;
targetcontrolname = "document.form1." + targetcontrolname;
第三:如何為控件添加雙擊事件?
用controlname.attributes.add(“屬性名稱”,“函數名稱或代碼”);
新聞熱點
疑難解答
圖片精選