一,代码如下:
服务器端:
protected void Page_Load(object sender, EventArgs e)
{
…………………….
……………………
//列表框右键菜单
listunitsource.Attributes.Add("onmousedown","popUp('listunitsource','itemmenu1');");
listunittarget.Attributes.Add("onmousedown", "popUp('listunittarget','itemmenu1');");
// listunitsource 和listunittarget为两个listbox
……………………
……………………
}
//右键粘贴
protected void ButtonPaste_Click(object sender, EventArgs e)
{
string strRight =unithidvalue1.Value; //隐藏text控件
string str = unithidvalue2.Value;
string[] arrRight = strRight.Split(new Char[] { ',' });
for (int i = 0; i < arrRight.Length; i++)
{
if (arrRight[i] != "")
{
ListItem x = new ListItem();
x.Text = arrRight[i];
x.Value = arrRight[i];
if (str == "listunitsource") listunitsource.Items.Add(x);
else if (str == "listunittarget") listunittarget.Items.Add(x);
}
}
}
二,要点和问题
(1)鼠标右键的响应:在listbox上实现鼠标点击事件listunitsource.Attributes.Add("onmousedown","popUp('listunitsource','itemmenu1');");
在listbox上添加add(),"onmousedown" 代表鼠标点击事件,popUp()也就是该事件所触发的客户端函数。客户端函数通过if (event.button == 0 || event.button==2) //button==0表示在遨游浏览器中右键的判断,button==2表示在IE中右键的判断 来判断鼠标事件,event.button 代表鼠标点击事件。
(2)直接在客户端将数据添加到listbox 在页面刷新后数据就会消失,因为未将数据写入服务器端,因此在粘贴功能函数中用到了document.getElementById(button).click(); //控制Button的click,即等价于点击Button
通过添加一个长宽均为0的button键(注意:button键的visable不能设为false,这样会使buttin键失去功能),通过button_click事件来实现在服务器端写入数据。
(3)客户端与服务器端传递数据的方法:在这里用的是添加隐藏text(此处勇HtmlInputHidden)控件来实现传递,在客户端通过将字符串加入控件 (ObjHid.value += substr +",";),中间用"," 隔开字符串,在服务器端获得控件的value,再通过Split函数来进行划分(string[] arrRight = strRight.Split(new Char[] { ',' });)获得每个字符串。
(4)str +=strsub[j]+"\t"中"\t"的用处:若不加,则粘贴到excel文档中时同一行的所有文字都会挤在同一格内,无论字符串之间有多少空格,比如”abc def hij”,若在字符串之间加上"\t"则在粘贴到excel中时字符串会分别占一格。
本文作者:zhayabusay的专栏 来源:http://blog.csdn.net/zhayabusay/
CIO之家 www.ciozj.com 微信公众号:imciow