ASP.NET html服务器控件button单击事件被触发两次的问题

xjune2014 2014-06-19 05:46:52
代码很简单,aspx代码如下

<form id="form1" runat="server">
<div>
<!--type=submit"-->
<button id="btnApply" runat="server" type="submit" onserverclick="btnApply_ServerClick">提交</button>
<input id="btnApply2" runat="server" type="submit" onserverclick="btnApply_ServerClick" value="提交2"/>
<asp:Button ID="btnApply3" runat="server" Text="提交3" OnClick="btnApply_ServerClick" />
</div>
</form>


aspx.cs代码如下

protected void btnApply_ServerClick(object sender, EventArgs e)
{
//using System.Diagnostics;
Debug.WriteLine(" aaa");
}


当单击第一个<button>时,服务端事件被调用两次,即"aaa"被输出两次,调试的过程中发现是两个不同的线程在调用这个事件代码,此代码换到另一台电脑的vs开发环境中问题依旧,排除是本机问题,这是什么情况啊,求科普
(补充IE8下会是两次,IE9没试,FireFox下是一次)
...全文
492 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
w20w20520 2015-12-15
  • 打赏
  • 举报
回复
引用 3 楼 webhermit100 的回复:
<button id="btnApply" runat="server" type="submit" onserverclick="btnApply_ServerClick">提交</button> 修改为 <button id="btnApply" runat="server" type="button" onserverclick="btnApply_ServerClick">提交</button> 不用说了,给分吧!
谢谢,同样的问题,解决了
webhermit100 2014-06-23
  • 打赏
  • 举报
回复
不结贴的,以后一概不回答任何问题
-烟花雨季 2014-06-23
  • 打赏
  • 举报
回复
submit提交一次,触发一个事件,onserverclick又触发一次事件,肯定会有两次啊 3L就可以啊 <button id="btnApply" runat="server" type="button" onserverclick="btnApply_ServerClick">提交</button>
schyu1314 2014-06-20
  • 打赏
  • 举报
回复
submit 会提交整个form  所以会触发多次
霜寒月冷 2014-06-20
  • 打赏
  • 举报
回复
引用 7 楼 insus 的回复:
Insus.NET就是在IE8 / 64bit OS下测试的。
发现你的截图工具很拽啊
xjune2014 2014-06-20
  • 打赏
  • 举报
回复
引用 7 楼 insus 的回复:
Insus.NET就是在IE8 / 64bit OS下测试的。
//using System.Diagnostics; Debug.WriteLine(" aaa"); 用Debug.WriteLine,Response.Write看不出来
insus 2014-06-20
  • 打赏
  • 举报
回复
Insus.NET就是在IE8 / 64bit OS下测试的。
xjune2014 2014-06-20
  • 打赏
  • 举报
回复
引用 5 楼 insus 的回复:
拷贝你的代码,测试,没有出现你所说的问题: 你这种写法,让Insus.NET想起: http://www.cnblogs.com/insus/p/3732075.html
在IE8 32/64位下会发生这种情况,FireFox不会,其它浏览器未测试
insus 2014-06-20
  • 打赏
  • 举报
回复
拷贝你的代码,测试,没有出现你所说的问题:



你这种写法,让Insus.NET想起:
http://www.cnblogs.com/insus/p/3732075.html
webhermit100 2014-06-19
  • 打赏
  • 举报
回复
LZ结贴率太低了,不结下次不回啦
webhermit100 2014-06-19
  • 打赏
  • 举报
回复
<button id="btnApply" runat="server" type="submit" onserverclick="btnApply_ServerClick">提交</button> 修改为 <button id="btnApply" runat="server" type="button" onserverclick="btnApply_ServerClick">提交</button> 不用说了,给分吧!
xjune2014 2014-06-19
  • 打赏
  • 举报
回复
引用 1 楼 tanghuawei 的回复:
因为onserverclick这个事件被注册了两次
不是,你把后面两个按钮删除再编译,事件一样被触发两次
tanghuawei 2014-06-19
  • 打赏
  • 举报
回复
因为onserverclick这个事件被注册了两次
ASP.NET常用代码 1. 打开新的窗口并传送参数: 传送参数: response.write("<script>window.open('*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"')Button1.Attributes.Add("onclick","return confirm('确认?')"); button.attributes.add("onclick","if(confirm('are you sure...?')){return true;}else{return false;}") 3.删除表格选定记录 int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex]; string deleteCmd = "DELETE from Employee where emp_id = " + intEmpID.ToString() 4.删除表格记录警告 private void DataGrid_ItemCreated(Object sender,DataGridItemEventArgs e) { switch(e.Item.ItemType) { case ListItemType.Item : case ListItemType.AlternatingItem : case ListItemType.EditItem: TableCell myTableCell; myTableCell = e.Item.Cells[14]; LinkButton myDeleteButton ; myDeleteButton = (LinkButton)myTableCell.Controls[0]; myDeleteButton.Attributes.Add("onclick","return confirm('您是否确定要删除这条信息');"); break; default: break; } } 5.点击表格行链接另一页 private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { //点击表格打开 if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) e.Item.Attributes.Add("onclick","window.open('Default.aspx?id=" + e.Item.Cells[0].Text + "');"); } 双击表格连接到另一页 在itemDataBind事件中 if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { string OrderItemID =e.item.cells[1].Text; ... e.item.Attributes.Add("ondblclick", "location.href='../ShippedGrid.aspx?id=" + OrderItemID + "'"); } 双击表格打开新一页 if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { string OrderItemID =e.item.cells[1].Text; ... e.item.Attributes.Add("ondblclick", "open('../ShippedGrid.aspx?id=" + OrderItemID + "')"); } ★特别注意:【?id=】 处不能为 【?id =】 6.表格超连接列传递参数 ' & name='<%# DataBinder.Eval(Container.DataItem, "数据字段2")%>' /> 7.表格点击改变颜色 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem) { e.Item.Attributes.Add("onclick","this.style.backgroundColor='#99cc00';this.style.color='buttontext';this.style.cursor='default';"); } 写在DataGrid的_ItemDataBound里 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem) { e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='#99cc00';this.style.color='buttontext';this.style.cursor='default';"); e.Item.Attributes.Add("onmouseout","this.style.backgroundColor='';this.style.color='';"); } 8.关于日期格式 日期格式设定 DataFormatString="{0:yyyy-MM-dd}" 我觉得应该在itembound事件中 e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd")) 9.获取错误信息并到指定页面 不要使用Response.Redirect,而应该使用Server.Transfer e.g // in global.asax protected void Application_Error(Object sender, EventArgs e) { if (Server.GetLastError() is HttpUnhandledException) Server.Transfer("MyErrorPage.aspx"); //其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :) } Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理 10.清空Cookie Cookie.Expires=[DateTime]; Response.Cookies("UserName").Expires = 0 11.自定义异常处理 //自定义异常处理类 using System; using System.Diagnostics; namespace MyAppException { /// /// 从系统异常类ApplicationException继承的应用程序异常处理类。 /// 自动将异常内容记录到Windows NT/2000的应用程序日志 /// public class AppException:System.ApplicationException { public AppException() { if (ApplicationConfiguration.EventLogEnabled) LogEvent("出现一个未知错误。"); } public AppException(string message) { LogEvent(message); } public AppException(string message,Exception innerException) { LogEvent(message); if (innerException != null) { LogEvent(innerException.Message); } } //日志记录类 using System; using System.Configuration; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; namespace MyEventLog { /// /// 事件日志记录类,提供事件日志记录支持 /// /// 定义了4个日志记录方法 (error, warning, info, trace) /// /// public class ApplicationLog { /// /// 将错误信息记录到Win2000/NT事件日志中 /// 需要记录的文本信息 /// public static void WriteError(String message) { WriteLog(TraceLevel.Error, message); } /// /// 将警告信息记录到Win2000/NT事件日志中 /// 需要记录的文本信息 /// public static void WriteWarning(String message) { WriteLog(TraceLevel.Warning, message); } /// /// 将提示信息记录到Win2000/NT事件日志中 /// 需要记录的文本信息 /// public static void WriteInfo(String message) { WriteLog(TraceLevel.Info, message); } /// /// 将跟踪信息记录到Win2000/NT事件日志中 /// 需要记录的文本信息 /// public static void WriteTrace(String message) { WriteLog(TraceLevel.Verbose, message); } /// /// 格式化记录到事件日志的文本信息格式 /// 需要格式化的异常对象 /// 异常信息标题字符串. /// /// 格式后的异常信息字符串,包括异常内容和跟踪堆栈. /// /// public static String FormatException(Exception ex, String catchInfo) { StringBuilder strBuilder = new StringBuilder(); if (catchInfo != String.Empty) { strBuilder.Append(catchInfo).Append("\r\n"); } strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace); return strBuilder.ToString(); } /// /// 实际事件日志写入方法 /// 要记录信息的级别(error,warning,info,trace). /// 要记录的文本. /// private static void WriteLog(TraceLevel level, String messageText) { try { EventLogEntryType LogEntryType; switch (level) { case TraceLevel.Error: LogEntryType = EventLogEntryType.Error; break; case TraceLevel.Warning: LogEntryType = EventLogEntryType.Warning; break; case TraceLevel.Inf LogEntryType = EventLogEntryType.Information; break; case TraceLevel.Verbose: LogEntryType = EventLogEntryType.SuccessAudit; break; default: LogEntryType = EventLogEntryType.SuccessAudit; break; } EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName ); //写入事件日志 eventLog.WriteEntry(messageText, LogEntryType); } catch {} //忽略任何异常 } } //class ApplicationLog } 12.Panel 横向滚动,纵向自动扩展 13.回车转换成Tab <script language="javascript" for="document" event="onkeydown"> if(event.keyCode==13 && event.srcElement.type!='button' && event.srcElement.type!='submit' && event.srcElement.type!='reset' && event.srcElement.type!=''&& event.srcElement.type!='textarea'); event.keyCode=9; 后台代码 protected void CheckAll_CheckedChanged(object sender, System.EventArgs e) { //改变列的选定,实现全选或全不选。 CheckBox chkExport ; if( CheckAll.Checked) { foreach(DataGridItem oDataGridItem in MyDataGrid.Items) { chkExport = (CheckBox)oDataGridItem.FindControl("chkExport"); chkExport.Checked = true; } } else { foreach(DataGridItem oDataGridItem in MyDataGrid.Items) { chkExport = (CheckBox)oDataGridItem.FindControl("chkExport"); chkExport.Checked = false; } } } 17.数字格式化 【<%#Container.DataItem("price")%>的结果是500.0000,怎样格式化为500.00?】 <%#Container.DataItem("price","{0:¥#,##0.00}")%> int i=123456; string s=i.ToString("###,###.00"); 18.日期格式化 【aspx页面内:<%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date")%> 显示为: 2004-8-11 19:44:28 我只想要:2004-8-11 】 <%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}")%> 应该如何改? 【格式化日期】 取出来,一般是object ((DateTime)objectFromDB).ToString("yyyy-MM-dd"); 【日期的验证表达式】 A.以下正确的输入格式: [2004-2-29], [2004-02-29 10:29:39 pm], [2004/12/31] ^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$ B.以下正确的输入格式:[0001-12-31], [9999 09 30], [2002/03/03] ^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$ 【大小写转换】 HttpUtility.HtmlEncode(string); HttpUtility.HtmlDecode(string) 19.如何设定全局变量 Global.asax中 Application_Start()事件中 添加Application[属性名] = xxx; 就是你的全局变量 20.怎样作到HyperLinkColumn生成的连接后,点击连接,打开新窗口? HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank") 【ASPNETMENU】点击菜单项弹出新窗口 在你的menuData.xml文件的菜单项中加入URLTarget="_blank" 如: ...... 最好将你的aspnetmenu升级到1.2版 21.委托讨论 http://community.csdn.net/Expert/topic/2651/2651579.xml?temp=.7183191 http://dev.csdn.net/develop/article/22/22951.shtm 22.读取DataGrid控件TextBox值 foreach(DataGrid dgi in yourDataGrid.Items) { TextBox tb = (TextBox)dgi.FindControl("yourTextBoxId"); tb.Text.... } 23.在DataGrid中有3个模板列包含Textbox分别为 DG_ShuLiang (数量) DG_DanJian(单价) DG_JinE(金额)分别在5.6.7列,要求在录入数量及单价的时候自动算出金额即:数量*单价=金额还要求录入时限制为数值型.我如何用客户端脚本实现这个功能? 〖思归〗 <script language="javascript"> function DoCal() { var e = event.srcElement; var row = e.parentNode.parentNode; var txts = row.all.tags("INPUT"); if (!txts.length || txts.length < 3) return; var q = txts[txts.length-3].value; var p = txts[txts.length-2].value; if (isNaN(q) || isNaN(p)) return; q = parseInt(q); p = parseFloat(p); txts[txts.length-1].value = (q * p).toFixed(2); } "; private static string ScriptEnd = "0) { DataGrid1.CurrentPageIndex += 1; curPageIndex-=1; } bind(); // DataGrid1数据绑定函数 直接页面跳转: int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值 if(aButton)di.Cells[8].Controls[0]).Attributes.Add("onclick","return confirm('确认删除此项吗?');"); } } } 3.2样式交替: ListItemType itemType = e.Item.ItemType; if (itemType == ListItemType.Item ) { e.Item.Attributes["onmouseout"] = "javascript:this.style.backgroundColor='#FFFFFF';"; e.Item.Attributes["onmouseover"] = "javascript:this.style.backgroundColor='#d9ece1';cursor='hand';" ; } else if( itemType == ListItemType.AlternatingItem) { e.Item.Attributes["onmouseout"] = "javascript:this.style.backgroundColor='#a0d7c4';"; e.Item.Attributes["onmouseover"] = "javascript:this.style.backgroundColor='#d9ece1';cursor='hand';" ; } 3.3添加一个编号列: DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable DataColumn dc=dt.Columns.Add("number",System.Type.GetType("System.String")); for(int i=0;i /// 服务器端弹出alert对话框 /// /// 提示信息,例子:"不能为空!" /// Page类 public void Alert(string str_Message,Page page) { page.RegisterStartupScript("","<script>alert('"+str_Message+"');控件获得焦点 /**//// /// 服务器端弹出alert对话框,并使控件获得焦点 /// /// 获得焦点控件Id值,比如:txt_Name /// 提示信息,例子:"请输入您姓名!" /// Page类 public void Alert(string str_Ctl_Name,string str_Message,Page page) { page.RegisterStartupScript("","<script>alert('"+str_Message+"');document.forms(0)."+str_Ctl_Name+".focus(); document.forms(0)."+str_Ctl_Name+".select(); /// 服务器端弹出confirm对话框 /// /// 提示信息,例子:"您是否确认删除!" /// 隐藏Botton按钮Id值,比如:btn_Flow /// Page类 public void Confirm(string str_Message,string btn,Page page) { page.RegisterStartupScript("","<script> if (confirm('"+str_Message+"')==true){document.forms(0)."+btn+".click();}触发一个隐藏按钮事件,点击取消触发一个隐藏按钮事件 /**//// /// 服务器端弹出confirm对话框,询问用户准备转向那些操作,包括“确定”和“取消”时的操作 /// /// 提示信息,比如:"成功增加数据,单击\"确定\"按钮填写流程,单击\"取消\"修改数据" /// "确定"按钮id值 /// "取消"按钮id值 /// Page类 public void Confirm(string str_Message,string btn_Redirect_Flow,string btn_Redirect_Self,Page page) { page.RegisterStartupScript("","<script> if (confirm('"+str_Message+"')==true){document.forms(0)."+btn_Redirect_Flow+".click();}else{document.forms(0)."+btn_Redirect_Self+".click();} /// 使控件获得焦点 /// /// 获得焦点控件Id值,比如:txt_Name /// Page类 public void GetFocus(string str_Ctl_Name,Page page) { page.RegisterStartupScript("","<script>document.forms(0)."+str_Ctl_Name+".focus(); document.forms(0)."+str_Ctl_Name+".select(); ///名称:redirect ///功能:子窗体返回主窗体 ///参数:url ///返回值:空 /// public void redirect(string url,Page page) { if ( Session["IfDefault"]!=(object)"Default") { page.RegisterStartupScript("","<script>window.top.document.location.href='"+url+"'; /// 名称:IsNumberic /// 功能:判断输入的是否是数字 /// 参数:string oText:源文本 /// 返回值: bool true:是 false:否 /// public bool IsNumberic(string oText) { try { int var1=Convert.ToInt32 (oText); return true; } catch { return false; } } 获得字符串实际长度(包括中文字符) //获得字符串oString的实际长度 public int StringLength(string oString) { byte[] strArray=System.Text .Encoding.Default .GetBytes (oString); int res=strArray.Length ; return res; } 42.将回车转换为TAB //当在有keydown事件控件上敲回车时,变为tab public void Tab(System.Web .UI.WebControls .WebControl webcontrol) { webcontrol.Attributes .Add ("onkeydown", "if(event.keyCode==13) event.keyCode=9"); } 43.datagrid分页中如果删除时出现超出索引 public void jumppage(System.Web.UI.WebControls.DataGrid dg) { int int_PageLess; //定义页面跳转的页数 //如果当前页是最后一页 if(dg.CurrentPageIndex == dg.PageCount-1) { //如果就只有一页 if(dg.CurrentPageIndex == 0) { //删除后页面停在当前页 dg.CurrentPageIndex = dg.PageCount-1; } else { //如果最后一页只有一条记录 if((dg.Items.Count % dg.PageSize == 1) || dg.PageSize == 1) { //把最后一页最后一条记录删除后,页面应跳转到前一页 int_PageLess = 2; } else //如果最后一页的记录数大于1,那么在最后一页删除记录后仍然停在当前页 { int_PageLess = 1; } dg.CurrentPageIndex = dg.PageCount - int_PageLess; } } } 发表于 2
2023/6/4 ASP.NETWeb服务器控件 ASP全文共74页,当前为第1页。 ASP.NET提供的Web效力器控件简化了Web运用顺序的设计进程。 Windows控件的属性、方法、事情都是在本机上执行的; Web效力器控件的属性、方法、事情那么全部是在效力器端执行的。 在Web运用顺序中,用户经过客户端阅读器操作Web页面时,对Web效力器控件的每个央求都要发送到效力器端,效力器中止处置后,再将处置结果转换为客户端脚本发送到客户端显示。 由于客户端的每个央求都要经过网络发送到效力器处置,会对网络传输带来很大的担负。 Windows控件与Web效劳器控件的主要区别 ASP全文共74页,当前为第2页。 14.1 规范控件 14.1.1 复杂控件 Button、TextBox、CheckBox CheckBoxList、RadioButton RadioButtonList、ListBox DropDownList 14.1.2 Table控件 14.1.3 HiddenField控件 ASP全文共74页,当前为第3页。 14.1.1 复杂控件 Button控件 有三种类型的按钮控件Button控件:与Windows窗体的Button控件用法相反。 LinkButton控件:外观与Hyperlink控件相反,但在功用上与Button控件完全相反。 ImageButton控件:经过属性[ImageUrl]指定显示在按钮的图片。 三种类型的按钮在鼠标单击时都可以将窗体提交给效力器,并触发效力器端对应的Click事情,然后在效力器端执行相应的事情代码。 ASP全文共74页,当前为第4页。 TextBox控件 TextBox控件用于在Web页面中接纳如入的文本内容。 1. 常用的基本属性 1) AutoPostBack属性:决议控件中文本修正后,能否自动回发到效力器。该属性默许值为false,即修注释本后并不立刻回发到效力器,而是等窗体被提交后一并处置。 2) TextMode属性:用于设置文本框接受文本的行为方式。共有三种属性值:MultiLine〔多行输入方式〕;Password〔密码输入方式〕;SingleLine〔单行输入方式〕。默许状况下,该属性为SingleLine。 2. 常用的事情 TextChanged事情:文本框的内容发作更改招致窗体回发效力器时触发。 留意,能否触发该事情与AutoPostBack属性有关。 ASP全文共74页,当前为第5页。 CheckBox控件与CheckBoxList控件  CheckBox控件:向用户提供一组可选项。 CheckBoxList控件:向用户提供一组选项,也叫复选框。在运转时静态的决议有哪些选项时,运用CheckBoxList控件比拟方便。 ASP全文共74页,当前为第6页。 CheckBox控件与CheckBoxList控件〔续〕 1. CheckBox控件的常用基本属性 AutoPostBack属性:决议CheckBox控件外形更改后能否自动回发到效力器处置。该属性默许值为false。 2. CheckBoxList控件的常用基本属性 1) Items属性:表示控件对象中一切项的集合。 2) RepeatColumns属性:指示控件中显示CheckBox项的列数。 3) RepeatDirection属性:决议控件中各CheckBox项的显示方法。默许值是Vertical。该属性值还可以修正为Horizontal,使各项按水平方式陈列显示。 3. CheckBoxList控件的常用基身手情 CheckedIndexChanged事情:更改CheckBoxList控件中的选项,回发效力器时触发。 ASP全文共74页,当前为第7页。 RadioButton控件与RadioButtonList控件 RadioButton效力器控件与Windows控件的区别: 在Windows窗体中,在同一容器中的一切RadioButton控件都默以为同一组,只能在这些控件中中止单项选择; Web窗体中,默许状况下会将同一容器中的一切RadioButton效力器控件作为不同组,可以多项选择。假定希望将其作为一组,需求设置RadioButton 的GroupName属性。 ASP全文共74页,当前为第8页。 RadioButton控件与RadioButtonList控件〔续〕 RadioButton控件的GroupName属性:运用该属性指定一个单项选择按钮组,以创立一组互斥的控件。 RadioButtonList效力器控件是封装了一组单项选择按钮控件的列表控件。其主要的属性、事情与CheckBoxList效力器控件相反。 ASP全文共74页,当前为第9页。 ListBox控件 ListBox
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.Drawing.Drawing2D; namespace KRT.Component.Common { /// /// 停靠面板控件 /// public class DockPanel : Panel { /// /// 关闭按钮 /// DockPanelCloseButton closeButton = new DockPanelCloseButton(); /// /// 浮动窗口 /// Form flowForm = new Form(); /// /// 分割栏 /// Splitter splitter = new Splitter(); /// /// 标题栏 /// Label titleBar = new Label(); /// /// 标题栏背景色 /// public Color TitleBackColor //using System.Drawing; { get { return titleBar.BackColor; } set { titleBar.BackColor = value; closeButton.BackColor = value; } } /// /// 标题栏前景色 /// public Color TitleForeColor { get { return titleBar.ForeColor; } set { titleBar.ForeColor = value; } } /// /// 标题栏文本 /// [Localizable(true)] public string TitleText { get { return titleBar.Text; } set { titleBar.Text = value; } } /// /// 标题栏可见 /// public bool TitleVisible { get { return titleBar.Visible; } set { titleBar.Visible = value; closeButton.Visible = value; } } /// /// 浮动窗口最大尺寸 /// Size flowFormMaxSize = new Size(640, 480); public Size FlowFormMaxSize { get { return flowFormMaxSize; } set { flowFormMaxSize = value; if (this.VisibleAll) { flowForm.Size = flowFormMaxSize; } } } /// /// 整个控件的隐藏、显示,包括浮动窗口状态下 /// bool visibleAll = true; public bool VisibleAll { get { return visibleAll; } set { visibleAll = value; if (flowForm.Controls.Count > 0) { flowForm.Visible = visibleAll; } else { this.Visible = visibleAll; } } } /// /// 控件初始化 /// public DockPanel() { //InitializeComponent(); flowForm.ShowInTaskbar = false; // 关闭按钮 closeButton.Location = new System.Drawing.Point(0, 0); closeButton.Name = "Close"; closeButton.Size = new System.Drawing.Size(16, 16); closeButton.TabIndex = 0; closeButton.BackColor = SystemColors.ControlDark; closeButton.Click += new EventHandler(closeButton_Click); // 浮动窗口 flowForm.FormBorderStyle = FormBorderStyle.SizableToolWindow; //VS2008自带的窗体设计器进行设置窗体的边框。 flowForm.ShowInTaskbar = false; //任务栏 flowForm.MaximizeBox = false; //最大化按钮 flowForm.Move += new EventHandler(flowForm_Move); //EventHandler是asp.net内置的委托,事件是特殊的委托。 flowForm.MouseCaptureChanged += new EventHandler(flowForm_MouseCaptureChanged); // flowForm.FormClosing += new FormClosingEventHandler(flowForm_FormClosing); // 标题栏 titleBar.AutoSize = false; //自动调整大小 titleBar.Dock = DockStyle.Top;//控件顶端;DockStyle是个枚举,有none, top, bottom... titleBar.Height = 18; titleBar.Padding = new Padding(3); titleBar.MouseDown += new MouseEventHandler(titleBar_MouseDown); titleBar.MouseMove += new MouseEventHandler(titleBar_MouseMove); titleBar.MouseUp += new MouseEventHandler(titleBar_MouseUp); //this.Padding = new Padding(1); this.Controls.Add(closeButton); this.Controls.Add(titleBar); this.ParentChanged += new EventHandler(DockPanel_ParentChanged); this.VisibleChanged += new EventHandler(DockPanel_VisibleChanged); this.MouseDown += new MouseEventHandler(titleBar_MouseDown); this.MouseMove += new MouseEventHandler(titleBar_MouseMove); this.MouseUp += new MouseEventHandler(titleBar_MouseUp); this.ControlAdded += new ControlEventHandler(DockPanel_ControlAdded); } /// /// 如果是用户单击浮动窗口的关闭按钮,隐藏浮动窗口 /// /// /// void flowForm_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; flowForm.Visible = false; visibleAll = false; closeButton_Click(sender, e); } } /// /// 添加子控件时调整顺序 /// /// /// void DockPanel_ControlAdded(object sender, ControlEventArgs e) { if (e.Control != titleBar && e.Control != closeButton) { e.Control.BringToFront(); } } /// /// 同时修改Splitter的可视效果 /// /// /// void DockPanel_VisibleChanged(object sender, EventArgs e) { splitter.Visible = Visible; if (this.Parent != null && Visible) { if (!this.DesignMode) { if (this.Parent.Controls.IndexOf(splitter) < 0) { //splitter.Dock = this.Dock; //this.Parent.Controls.AddRange(new Control[] { splitter, this }); this.Parent.Controls.Add(splitter); int index = this.Parent.Controls.IndexOf(this); this.Parent.Controls.SetChildIndex(splitter, index); //this.Parent.Controls.SetChildIndex(this, index + 1); //foreach (Control item in this.Parent.Controls) //{ // Debug.WriteLine( // this.Parent.Controls.GetChildIndex(item).ToString() + " : " + // item.ToString()); //} } } } } /// /// 初始化Splitter /// /// /// void DockPanel_ParentChanged(object sender, EventArgs e) { //if (this.Parent != null) //{ // if (!this.DesignMode) // { // //Parent.Controls.Add(splitter); // splitter.Dock = this.Dock; // this.Parent.Controls.AddRange(new Control[] { splitter, this }); // } //} } /// /// 关闭事件 /// public event EventHandler CloseButtonClick; /// /// 单击关闭按钮,触发关闭事件 /// /// /// void closeButton_Click(object sender, EventArgs e) { VisibleAll = false; if (null != CloseButtonClick) { CloseButtonClick(sender, e); } } /// /// 浮动窗口开始拖动时触发 /// /// /// void flowForm_MouseCaptureChanged(object sender, EventArgs e) { if (!flowFormCapture) { flowFormCapture = true; } else { flowFormCapture = false; flowFormDock = true; } } bool flowFormDock = false; // 浮动窗口可以被停靠 bool flowFormCapture = false; // 浮动窗口开始拖动 /// /// 浮动窗口移动过程 /// /// /// void flowForm_Move(object sender, EventArgs e) { if (flowFormDock) { flowFormDock = false; switch (this.Dock) { case DockStyle.Left: if (flowForm.Location.X < Parent.Location.X) { ShowDockPanel(); } break; case DockStyle.Top: if (flowForm.Location.Y Parent.Location.X + Parent.Width) { ShowDockPanel(); } break; case DockStyle.Bottom: if (flowForm.Location.Y + flowForm.Height > Parent.Location.Y + Parent.Height) { ShowDockPanel(); } break; } } } /// /// 控件尺寸改变 /// /// protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); closeButton.Location = new Point( ClientRectangle.Right - closeButton.Width - 1, 1); closeButton.Refresh(); } Point oldMouseLocation; // 鼠标位置 Rectangle rect; // 面板区域 bool mouseDown = false; // 鼠标按下 /// /// 鼠标按下事件 /// /// /// void titleBar_MouseDown(object sender, MouseEventArgs e) { if (this.Dock != DockStyle.None && this.Dock != DockStyle.Fill) { oldMouseLocation = e.Location; mouseDown = true; rect = this.RectangleToScreen(ClientRectangle); ControlPaint.DrawReversibleFrame(rect, Color.Black, FrameStyle.Thick); } } /// /// 鼠标移动事件 /// /// /// void titleBar_MouseMove(object sender, MouseEventArgs e) { if (mouseDown) { ControlPaint.DrawReversibleFrame(rect, Color.Black, FrameStyle.Thick); rect.Offset(e.X - oldMouseLocation.X, e.Y - oldMouseLocation.Y); oldMouseLocation = e.Location; ControlPaint.DrawReversibleFrame(rect, Color.Black, FrameStyle.Thick); } } /// /// 鼠标弹起事件 /// /// /// void titleBar_MouseUp(object sender, MouseEventArgs e) { if (mouseDown) { mouseDown = false; ControlPaint.DrawReversibleFrame(rect, Color.Black, FrameStyle.Thick); Rectangle rc = this.RectangleToScreen(ClientRectangle); Point pt = this.PointToScreen(e.Location); if (!rc.Contains(pt)) { ShowFlowForm(); } } } //protected override void OnPaint(PaintEventArgs e) //{ // base.OnPaint(e); // Pen borderPen = new Pen(borderColor); // Rectangle rc = new Rectangle( // e.ClipRectangle.Left, e.ClipRectangle.Top, // e.ClipRectangle.Right - 1, e.ClipRectangle.Bottom - 1); // e.Graphics.DrawRectangle(borderPen, rc); //} /// /// 显示浮动窗口 /// void ShowFlowForm() { flowForm.Show(Parent); flowForm.Location = new Point(rect.Left, rect.Top); Size newSize = new Size(rect.Width, rect.Height); if (newSize.Width > FlowFormMaxSize.Width) { newSize.Width = FlowFormMaxSize.Width; } newSize.Height = newSize.Height + (this.TitleVisible ? SystemInformation.CaptionHeight - this.titleBar.Height : SystemInformation.CaptionHeight); if (newSize.Height > FlowFormMaxSize.Height) { newSize.Height = FlowFormMaxSize.Height; } flowForm.Size = newSize; flowForm.Text = TitleText; while (this.Controls.Count > 2) { for (int i = 0; i < this.Controls.Count; i++) { if (this.Controls[i] != closeButton && this.Controls[i] != titleBar) { flowForm.Controls.Add(this.Controls[i]); break; } } } this.Visible = false; } /// /// 显示停靠面板 /// void ShowDockPanel() { this.Visible = true; while (flowForm.Controls.Count > 0) { this.Controls.Add(flowForm.Controls[0]); } flowForm.Hide(); } } }

62,072

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧