关于TextBox1.Attributes.Add的问题

---問題---------
我的页面上分别有两个按钮Button1,Button2,和两个编辑框TextBox1,TextBox2,我在PAGE_LOAD里加上下面这行代码后,  
   
TextBox1.Attributes.Add("onkeydown","if(event.keyCode==13){document.all.Button1.click();}");  
   
实现了对TextBox1进行编辑的时候敲ENDER直接执行Button1.click的代码,但是我发现这时候对  
TextBox2进行编辑的时候敲ENDER也会直接执行Button1.click的代码.  
   
于是我又在PAGE_LOAD里加上  
   
TextBox2.Attributes.Add("onkeydown","if(event.keyCode==13){document.all.Button2.click();}");  
   
但是对TextBox2进行编辑的时候敲ENDER仍然会直接执行Button1.click的代码.而不执行Button2.click的代码  
   
而且现在即使我把这两条语句删除掉,再对TextBox1,TextBox2进行编辑,点击ENDER还是会直接执行Button1.click的代码.  
   
想问一下这种情况是因为什么,要怎么样才能解决和避免这种情况.


---出現此情況的原因------------
这是由于WEB表单的特性决定的,Button1是表单的默认提交按钮,只要是在这个表单内,除多行文本框外的所有控件上回车,都会激发Button1

。所以会出现这种情况!!!  

 

---解决辦法---------------
在PAGE_LOAD里加上
Me.txtApplyID.Attributes.Add("onkeydown", "if(event.keyCode==13){document.all." + butQuery.ClientID + ".click();return   false}")
Me.txtCHANGEID.Attributes.Add("onkeydown", "if(event.keyCode==13){document.all." + butQuery.ClientID + ".click();return   false}")

txtApplyID是輸入框,輸入結束按回車,然後執行後面的butQuery按鈕。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET程序中常用的三十三种代码 1. 打开新的窗口并传送参数:   传送参数: response.write("window.open(’*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)")   接收参数: string a = Request.QueryString("id"); string b = Request.QueryString("id1");   2.为按钮添加对话 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.表格超连接列传递参数 <asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" NavigateUrl="aaa.aspx?id=’  ’ & name=’’ />   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.Info:        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  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; onkeydown="if(event.keyCode==13) event.keyCode=9"   14.DataGrid超级连接列 DataNavigateUrlField="字段名" DataNavigateUrlFormatString="http://xx/inc/delete.aspx?ID={0}"   15.DataGrid行随鼠标变色 private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) {  if (e.Item.ItemType!=ListItemType.Header)  {   e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor=\""+e.Item.Style["BACKGROUND-COLOR"]+"\"");   e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor=\""+ "#EFF3F7"+"\"");  } }   16.模板列 <ASP:LABEL text=’’ runat="server" width="80%" id="lblColumn" />   后台代码 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.数字格式化   【的结果是500.0000,怎样格式化为500.00?】 int i=123456; string s=i.ToString("###,###.00");   18.日期格式化   【aspx页面内:   显示为: 2004-8-11 19:44:28   我只想要:2004-8-11 】   应该如何改?   【格式化日期】   取出来,一般是 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.读取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列,要求在录入数量及单价的时候自动算出金额即:数量*单价=金额还要求录入时限制为 数值型.我如何用客户端脚本实现这个功能?   〖思归〗 <asp:TextBox id="ShuLiang" runat=’server’ Text=’’ onkeyup="javascript:DoCal()" /> <asp:TextBox id="DanJian" runat=’server’ Text=’’ onkeyup="javascript:DoCal()" /> <asp:TextBox id="JinE" runat=’server’ Text=’’ /> 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); }   24.datagrid选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看不到了。 page_load page.smartNavigation=true   25.在Datagrid中修改数据,当点击编辑键时,数据出现在文本框中,怎么控制文本框的大小 ? private void DataGrid1_ItemDataBound(obj sender,DataGridItemEventArgs e) {  for(int i=0;i<e.Item.Cells.Count-1;i++)   if(e.Item.ItemType==ListItemType.EditType)   {    e.Item.Cells[i].Attributes.Add("Width", "80px")   } }   26.对话 private static string ScriptBegin = ""; private static string ScriptEnd = ""; public static void ConfirmMessageBox(string PageTarget,string Content) {  string ConfirmContent="var retValue=window.confirm(’"+Content+"’);"+"if(retValue){window.location=’"+PageTarget+"’;}";  ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;  Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler;  ParameterPage.RegisterStartupScript("confirm",ConfirmContent);  //Response.Write(strScript); }   27. 将时间格式化:string aa=DateTime.Now.ToString("yyyy年MM月dd日");   1.1 取当前年月日时分秒 currentTime=System.DateTime.Now;   1.2 取当前年 int 年= DateTime.Now.Year;   1.3 取当前月 int 月= DateTime.Now.Month;   1.4 取当前日 int 日= DateTime.Now.Day;   1.5 取当前时 int 时= DateTime.Now.Hour;   1.6 取当前分 int 分= DateTime.Now.Minute;   1.7 取当前秒 int 秒= DateTime.Now.Second;   1.8 取当前毫秒 int 毫秒= DateTime.Now.Millisecond;   28.自定义分页代码:   先定义变量 : public static int pageCount; //总页面数 public static int curPageIndex=1; //当前页面   下一页: if(DataGrid1.CurrentPageIndex 0) {  DataGrid1.CurrentPageIndex += 1;  curPageIndex-=1; } bind(); // DataGrid1数据绑定函数   直接页面跳转: int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值 if(a<DataGrid1.PageCount) {  this.DataGrid1.CurrentPageIndex=a; } bind();   29.DataGrid使用:   添加删除确认: private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) {  foreach(DataGridItem di in this.DataGrid1.Items)  {   if(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)   {    ((LinkButton)di.Cells[8].Controls[0]).Attributes.Add("onclick","return confirm(’确认删除此项吗?’);");   }  } }   样式交替: 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’;" ; }   添加一个编号列: DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable DataColumn dc=dt.Columns.Add("number",System.Type.GetType("System.String")); for(int i=0;i<dt.Rows.Count;i++) {  dt.Rows[i]["number"]=(i+1).ToString(); } DataGrid1.DataSource=dt; DataGrid1.DataBind();   DataGrid1中添加一个CheckBox,页面中添加一个全选 private void CheckBox2_CheckedChanged(object sender, System.EventArgs e) {  foreach(DataGridItem thisitem in DataGrid1.Items)  {   ((CheckBox)thisitem.Cells[0].Controls[1]).Checked=CheckBox2.Checked;  } }   将当前页面中DataGrid1显示的数据全部删除 foreach(DataGridItem thisitem in DataGrid1.Items) {  if(((CheckBox)thisitem.Cells[0].Controls[1]).Checked)  {   string strloginid= DataGrid1.DataKeys[thisitem.ItemIndex].ToString();   Del (strloginid); //删除函数  } }   30.当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在Web.config,然后在Global.asax中初始化)   在Application_Start中添加以下代码: Application["ConnStr"]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.    AppSettings["ConnStr"].ToString();   31. 变量.ToString()   字符型转换 转为字符串 12345.ToString("n"); //生成 12,345.00 12345.ToString("C"); //生成 ¥12,345.00 12345.ToString("e"); //生成 1.234500e+004 12345.ToString("f4"); //生成 12345.0000 12345.ToString("x"); //生成 3039 (16进制) 12345.ToString("p"); //生成 1,234,500.00%   32、变量.Substring(参数1,参数2);   截取字串的一部分,参数1为左起始位数,参数2为截取几位。 如:string s1 = str.Substring(0,2);   33.在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个FORM,这时可以导向另外一个页面再提交登陆信息)   文本框的名称必须是你要登陆的网页上的名称,如果源码不行可以用vsniffer 看看。   下面是获取用户输入的登陆信息的代码: string name; name=Request.QueryString["EmailName"]; try {  int a=name.IndexOf("@",0,name.Length);  f_user.Value=name.Substring(0,a);  f_domain.Value=name.Substring(a+1,name.Length-(a+1));  f_pass.Value=Request.QueryString["Psw"]; } catch {  Script.Alert("错误的邮箱!");  Server.Transfer("index.aspx"); }
Contents xvii Web Forms 133 Intellisense 134 Customizing the IDE 135 Customizing the Code Editor 135 Customizing Shortcut Keys 135 Customizing the Toolbars 136 Exercise 3.4 Adding a New Toolbar to the Existing Set 136 Exercise 3.5 Adding Commands to Toolbars 137 Customizing Built-In Commands 137 Exercise 3.6 Creating an Alias 138 Customizing the Start Page 139 Accessibility Options 141 Summary 142 Solutions Fast Track 142 Frequently Asked Questions 143 Chapter 4 Common Language Runtime 145 Introduction 146 Component Architecture 148 Managed Code versus Unmanaged Code 150 Interoperability with Managed Code 152 System Namespace 153 File I/O 155 Drawing 156 Printing 157 Common Type System 158 Type Casting 160 Garbage Collection 163 Object Allocation/Deallocation 164 Close/Dispose 165 Summary 166 Solutions Fast Track 167 Frequently Asked Questions 168 Developing & Deploying… Embrace Your Parameters VB.NET is insistent upon enclosing parameters of function calls within parentheses regardless of whether we are returning a value or whether we are using the Call statement. It makes the code much more readable and is a new standard for VB programmers that is consistent with the standard that nearly all other languages adopted long ago. 153_VBnet_TOC 8/16/01 1:12 PM Page xvii xviii Contents Chapter 5 .NET Programming Fundamentals 171 Introduction 172 Variables 173 Constants 175 Structures 176 Program Flow Control 178 If…Then…Else 178 Select Case 182 While Loops 184 For Loops 186 Arrays 187 Declaring an Array 188 Multidimensional Arrays 189 Dynamic Arrays 191 Functions 192 Object Oriented Programming 196 Inheritance 196 Polymorphism 197 Encapsulation 197 Classes 198 Adding Properties 198 Adding Methods 200 System.Object 201 Constructors 201 Overloading 202 Overriding 203 Shared Members 205 String Handling 206 Error Handling 210 Summary 213 Solutions Fast Track 214 Frequently Asked Questions 217 NOTE When porting Visual Basic applications to Visual Basic .NET, be careful of the lower bounds of arrays. If you are using a for loop to iterate through the array, and it is hard-coded to initialize the counter at 1, the first element will be skipped. Remember that all arrays start with the index of 0. 153_VBnet_TOC 8/16/01 1:12 PM Page xviii Contents xix Chapter 6 Advanced Programming Concepts 219 Introduction 220 Using Modules 221 Utilizing Namespaces 222 Creating Namespaces 222 Understanding the Imports Keyword 226 Implementing Interfaces 229 Delegates and Events 232 Simple Delegates 235 Multicast Delegates 236 Event Programming 236 Handles Keyword 236 Language Interoperability 237 File Operations 239 Directory Listing 239 Data Files 241 Text Files 243 Appending to Files 246 Collections 246 The Drawing Namespace 248 Images 253 Printing 256 Understanding Free Threading 262 SyncLock 263 Summary 265 Solutions Fast Track 265 Frequently Asked Questions 267 Chapter 7 Creating Windows Forms 269 Introduction 270 Application Model 270 Properties 271 Manipulating Windows Forms 275 Properties of Windows Forms 275 Methods of Windows Forms 276 Creating Windows Forms 287 What Are Collections? Collectionsare groups of like objects. Collections are similar to arrays, but they don’t have to be redimensioned. You can use the Addmethod to add objects to a collection. Collections take a little more code to create than arrays do, and sometimes accessing a collection can be a bit slower than an array, but they offer significant advantages because a collection is a group of objects whereby an array is a data type. 153_VBnet_TOC 8/16/01 1:12 PM Page xix xx Contents Displaying Modal Forms 288 Displaying Modeless Forms 289 Displaying Top-Most Forms 289 Changing the Borders of a Form 289 Resizing Forms 291 Setting Location of Forms 292 Form Events 294 Creating Multiple Document Interface Applications 297 Creating an MDI Parent Form 297 Creating MDI Child Forms 298 Exercise 7.1 Creating an MDI Child Form 298 Determining the Active MDI Child Form 299 Arranging MDI Child Forms 299 Adding Controls to Forms 300 Anchoring Controls on Forms 301 Docking Controls on Forms 303 Layering Objects on Forms 304 Positioning Controls on Forms 304 Dialog Boxes 305 Displaying Message Boxes 306 Common Dialog Boxes 306 The OpenFileDialog Control 306 The SaveFileDialog Control 309 The FontDialog Control 311 The ColorDialog Control 313 The PrintDialog Control 315 The PrintPreviewDialog Control 316 The PageSetupDialog Control 321 Creating Dialog Boxes 322 Creating and Working with Menus 323 Adding Menus to a Form 323 Exercise 7.2 Adding a Menu to a Form at Design Time 323 Creating Dialog Boxes 1.Create a form. 2.Set the BorderStyle property of the form to FixedDialog. 3.Set the ControlBox, MinimizeBox, and MaximizeBox properties of the form to False. 4.Customize the appearance of the form appropriately. 5.Customize event handlers in the Code window appropriately. 153_VBnet_TOC 8/16/01 1:12 PM Page xx Contents xxi Dynamically Creating Menus 326 Exercise 7.3 Adding a Menu to a Form at Design Time 326 Adding Status Bars to Forms 328 Adding Toolbars to Forms 330 Data Binding 332 Simple Data Binding 332 Complex Data Binding 333 Data Sources for Data Binding 333 Using the Data Form Wizard 334 Using the Windows Forms Class Viewer 338 Using the Windows Forms ActiveX Control Importer 338 Summary 340 Solutions Fast Track 340 Frequently Asked Questions 344 Chapter 8 Windows Forms Components and Controls 347 Introduction 348 Built-In Controls 348 Label Control 351 LinkLabel Control 354 TextBox Control 357 Button Control 361 CheckBox Control 364 RadioButton Control 365 RichTextBox Control 367 TreeView Control 369 ListBox Control 371 CheckedListBox Control 374 ListView Control 376 ComboBox Control 381 DomainUpDown Control 384 NumericUpDown Control 386 PictureBox Control 388 TrackBar Control 389 Adding Items to a Combo Box at Design-Time 1.Select the ComboBox control on the form. 2.If necessary, use the Viewmenu to open the Properties window. 3.In the Properties window, click the Itemsproperty, then click the ellipsis. 4.In String Collection Editor, type the first item, then press Enter. 5.Type the next items, pressing Enterafter each item. 6.Click OK. 153_VBnet_TOC 8/16/01 1:13 PM Page xxi xxii Contents DateTimePicker Control 391 Panel Control 394 GroupBox Control 396 TabControl Control 397 Creating Custom Windows Components 399 Exercise 8.1:Creating a Custom Windows Component 399 Creating Custom Windows Controls 403 Exercise 8.2:Creating a Custom Windows Control 404 Summary 407 Solutions Fast Track 407 Frequently Asked Questions 408 Chapter 9 Using ADO.NET 409 Introduction 410 Overview of XML 411 XML Documents 411 XSL 411 XDR 412 XPath 412 Understanding ADO.NET Architecture 412 Differences between ADO and ADO.NET 414 XML Support 414 ADO.NET Configuration 415 Remoting in ADO.NET 415 Maintaining State 415 Using the XML Schema Definition Tool 416 Connected Layer 417 DataProviders 418 Connection Strings 418 Exercise 9.1 Creating a Connection String 419 Command Objects 421 DataReader 425 DataSet 426 XML Documents XML documents are the heart of the XML standard. An XML document has at least one element that is delimited with one start tag and one end tag. XML documents are similar to HTML, except that the tags are made up by the author. 153_VBnet_TOC 8/16/01 1:13 PM Page xxii Contents xxiii Disconnected Layer 427 Using DataSet 428 Relational Schema 428 Collection of Tables 430 Data States 431 Populating with the DataSet Command 432 Populating with XML 433 Populating Programmatically 434 Using the SQL Server Data Provider 435 TDS 436 Exercise 9.2 Using TypedDataSet 437 Remoting 439 Data Controls 440 DataGrid 440 Exercise 9.3 Using TypedDataSet and DataRelation 441 DataList 446 Repeater 450 Summary 454 Solutions Fast Track 454 Frequently Asked Questions 457 Chapter 10 Developing Web Applications 459 Introduction 460 Web Forms 461 A Simple Web Form 462 Exercise 10.1 Creating a Simple Web Form 462 How Web Forms Differ from Windows Forms 464 Why Web Forms Are Better Than Classic ASP 465 Adding Controls to Web Forms 467 Exercise 10.2 Adding Web Controls to a Web Form 468 Code Behind 473 NOTE Web form controls not only detect browsers such as Internet Explorer and Netscape, but they also detect devices such as Palm Pilots and cell phones and generate appropriate HTML accordingly. 153_VBnet_TOC 8/16/01 1:13 PM Page xxiii xxiv Contents How Web Form Controls Differ from Windows Form Controls 476 ASP.NET Server Controls 476 Intrinsic Controls 476 Bound Controls 478 Exercise 10.3 Using the DataGrid Control 478 Exercise 10.4 Customizing DataGrid Control 482 Custom Controls 487 Validation Controls 488 Exercise 10.5 Using the Validation Controls 489 Creating Custom Web Form Controls 492 Exercise 10.6 A Simple Custom Control 493 Exercise 10.7 Creating a Composite Custom Control 497 Web Services 504 How Web Services Work 505 Developing Web Services 505 Exercise 10.8 Developing Web Services 507 Web Service Utilities 509 Service Description Language 509 Discovery 510 Proxy Class 510 Consuming Web Services from Web Forms 511 Exercise 10.9 Consuming Web Services from Web Forms 511 Using Windows Forms in Distributed Applications 513 Exercise 10.10 Consuming Web Services from Windows Forms 514 Exercise 10.11 Developing a Sample Application 516 Summary 519 Solutions Fast Track 519 Frequently Asked Questions 521 153_VBnet_TOC 8/16/01 1:13 PM Page xxiv Contents xxv Chapter 11 Optimizing, Debugging, and Testing 523 Introduction 524 Debugging Concepts 524 Debug Menu 528 Watches 529 Breakpoints 531 Exceptions Window 532 Command Window 534 Conditional Compilation 536 Trace 538 Assertions 540 Code Optimization 541 Finalization 542 Transitions 542 Parameter Passing Methods 542 Strings 543 Garbage Collection 544 Compiler Options 544 Optimization Options 544 Output File Options 544 .NET Assembly Options 545 Preprocessor Options 546 Miscellaneous Options 546 Testing Phases and Strategies 546 Unit Testing 547 Integration Testing 547 Beta Testing 547 Regression Testing 548 Stress Testing 548 Monitoring Performance 548 Summary 550 Solutions Fast Track 551 Frequently Asked Questions 552 What Are Watches? Watchesprovide us with a mechanism where we can interact with the actual data that is stored in our programs at runtime. They allow us to see the values of variables and the values of properties on objects. In addition to being able to view these values, you can also assign new values. 153_VBnet_TOC 8/16/01 1:13 PM Page xxv xxvi Contents Chapter 12 Security 553 Introduction 554 Security Concepts 555 Permissions 555 Principal 556 Authentication 557 Authorization 557 Security Policy 558 Type Safety 558 Code Access Security 558 .NET Code Access Security Model 559 Stack Walking 559 Code Identity 561 Code Groups 562 Declarative and Imperative Security 564 Requesting Permissions 565 Demanding Permissions 570 Overriding Security Checks 572 Custom Permissions 576 Role-Based Security 578 Principals 578 WindowsPrincipal 579 GenericPrincipal 580 Manipulating Identity 581 Role-Based Security Checks 583 Security Policies 585 Creating a New Permission Set 588 Modifying the Code Group Structure 593 Remoting Security 600 Cryptography 600 Security Tools 603 Summary 606 Solutions Fast Track 607 Frequently Asked Questions 611 Within the .NET Framework, Three Namespaces Involve Cryptography 1.System.Security .CryptographyThe most important one; resembles the CryptoAPI functionalities. 2.System.Security .Cryptography.X509 certificatesRelates only to the X509 v3 certificate used with Authenticode. 3.System.Security .Cryptography.XmlFor exclusive use within the .NET Framework security system. 153_VBnet_TOC 8/16/01 1:13 PM Page xxvi Contents xxvii Chapter 13 Application Deployment 615 Introduction 616 Packaging Code 617 Configuring the .NET Framework 622 Creating Configuration Files 622 Machine/Administrator Configuration Files 623 Application Configuration Files 625 Security Configuration Files 626 Deploying the Application 629 Common Language Runtime 629 Windows Installer 630 CAB Files 631 Internet Explorer 5.5 632 Resource Files 633 Deploying Controls 637 Summary 639 Solutions Fast Track 640 Frequently Asked Questions 642 Chapter 14 Upgrading Visual Basic Applications to .NET 647 Introduction 648 Considerations Before Upgrading 648 Early Binding of Variables 649 Avoiding Null Propagation 650 Using ADO 651 Using Date Data Type 652 Using Constants 652 Considering Architecture Before Migration 653 Intranet/Internet Applications 653 Internet Information Server (IIS) Applications 654 DHTML Applications 655 ActiveX Documents 655 Client/Server and Multi-Tier Applications 655 Single-Tier Applications 656 Data Access Applications 656 WARNING You should under no circumstance edit the Security.config and Enterprise.config files directly. It is very easy to compromise the integrity of these files. Always use the Code Access Security Policy utility (caspol.exe) or the .NET Configuration tool; these will guard the integrity of the files and will also make a backup copy of the last saved version. 153_VBnet_TOC 8/16/01 1:13 PM Page xxvii xxviii Contents Data Types 657 Variants 657 Integers 658 Dates 658 Boolean 659 Arrays 659 Fixed-Length Strings 660 Windows API Data Types 661 Converting VB Forms to Windows Forms 662 Control Anchoring 664 Keyword Changes 665 Goto 666 GoSub 666 Option Base 666 AND/OR 666 Lset 666 VarPtr 667 StrPtr 667 Def 667 Programming Differences 668 Method Implementation 668 Optional Parameters 668 Static Modifier 669 Return Statement 669 Procedure Calls 670 External Procedure Declaration 671 Passing Parameters 672 ParamArray 672 Overloading 674 References to Unmanaged Libraries 677 Metadata 679 Runtime Callable Wrapper 681 COM Callable Wrapper 682 Properties 684 Working with Property Procedures 684 Control Property Name Changes 685 Default Property 687 Avoiding Null Propagation Nullpropagation means that if Null is used in an expression, the resulting expression is always Null. In previous versions of Visual Basic, the Null value disseminated throughout the expression. 153_VBnet_TOC 8/16/01 1:13 PM Page xxviii Contents xxix Null Usage 690 Understanding Error Handling 690 Exercise 14.1:Using Error Handling 692 Data Access Changes in Visual Basic .NET 693 Dataset and Recordset 694 Application Interoperability 694 Cursor Location 695 Disconnected Access 695 Data Navigation 695 Lock Implementation 696 Upgrading Interfaces 696 Upgrading Interfaces from Visual Basic 6.0 699 Using the Upgrade Tool 703 Exercise 14.2 Using the Upgrade Wizard 703 Summary 708 Solutions Fast Track 709 Frequently Asked Questions 712 Index 713 Contents xiii From the Series Editor xxxi Chapter 1 New Features in Visual Basic .NET 1 Introduction 2 Examining the New IDE 3 Cosmetic Improvements 3 Development Accelerators 5 .NET Framework 6 A Very Brief and Simplified History 6 .NET Architecture 7 ASP.NET 7 Framework Classes 8 .NET Servers 8 Common Language Runtime 8 History 8 Convergence 9 Object-Oriented Language 10 Object-Oriented Concepts 10 Advantages of Object-Oriented Design 11 History of Object Orientation and VB 13 Namespaces 13 Web Applications 13 Web Applications Overview 13 Web Forms 14 Web Services 15 HyperText Transport Protocol 16 Simple Object Access Protocol 17 .NET Architecture .NET Framework ASP.NET Updated ASP Engine Web Forms Engine Framework Classes System.Math, System.Io, System.Data, Etc. Common Language Runtime Memory Management Common Type System Garbage Collection .NET .NET Servers 153_VBnet_TOC 8/16/01 1:12 PM Page xiii xiv Contents Security 17 Type Safety 18 Casting 18 Data Conversion 19 Bitwise Operations 20 New Compiler 20 Compiling an Executable 20 Architecture 21 File Management in Previous Versions of VB 21 File Management 22 Changes from Visual Basic 6.0 23 Variants 23 Variable Lower Bounds 23 Fixed Length Strings 23 NULL Propagation 23 Other Items Removed 24 Function Values 24 Short Circuits 25 Properties and Variables 25 Variable Lengths 25 Get and Set 26 Date Type 26 Default Properties 27 Summary 28 Solutions Fast Track 28 Frequently Asked Questions 31 Chapter 2 The Microsoft .NET Framework 33 Introduction 34 What Is the .NET Framework? 34 Introduction to the Common Language Runtime 35 Using .NET-Compliant Programming Languages 37 Creating Assemblies 39 Using the Manifest 42 Compiling Assemblies 45 Assembly Cache 45 Locating an Assembly 45 153_VBnet_TOC 8/16/01 1:12 PM Page xiv Contents xv Private Assembly Files 51 Shared Assembly Files 51 Understanding Metadata 51 The Benefits of Metadata 52 Identifying an Assembly with Metadata 53 Types 53 Defining Members 54 Using Contracts 54 Assembly Dependencies 55 Unmanaged Assembly Code 55 Reflection 56 Attributes 57 Ending DLL Hell 58 Side-by-Side Deployment 58 Versioning Support 59 Using System Services 60 Exception Handling 60 StackTrace 61 InnerException 61 Message 61 HelpLink 62 Garbage Collection 62 Console I/O 62 Microsoft Intermediate Language 63 The Just-In-Time Compiler 63 Using the Namespace System to Organize Classes 64 The Common Type System 65 Type Safety 68 Relying on Automatic Resource Management 68 The Managed Heap 69 Garbage Collection and the Managed Heap 71 Assigning Generations 77 Utilizing Weak References 77 Security Services 79 Framework Security 80 Granting Permissions 81 NOTE Visualization is still key! Die-hard VB programmers may find themselves having a hard time visualizing all the new concepts in VB.NET (and we all know that proper logic visualization plays a big role in what we do). Something that may help is to think about VB.NET as a completely flexible language that can accommodate Web, console, and desktop use. 153_VBnet_TOC 8/16/01 1:12 PM Page xv xvi Contents Gaining Representation through a Principal 82 Security Policy 83 Summary 85 Solutions Fast Track 85 Frequently Asked Questions 88 Chapter 3 Installing and Configuring VB.NET 91 Introduction 92 Editions 92 Installing Visual Studio .NET 93 Exercise 3.1:Installing Visual Studio .NET 94 Installing on Windows 2000 99 The New IDE 100 Integrated Development Environment Automation Model 100 Add-Ins 104 Exercise 3.2 Creating an Add-In Using the Add-In Wizard 105 Wizards 109 Macros 109 Home Page 110 Project Options 112 Toolbox 116 Child Windows 120 Window Types 122 Arranging Windows 123 Task List 123 Exercise 3.3 Setting Up a Custom Token 124 TaskList Views 124 Locating Code 126 Annotating Code 126 Solution Explorer 127 Properties Window 129 Form Layout Toolbar 130 Hide/Show Code Elements 132 Installing Visual Studio .NET IPhase 1: Installing Windows components IPhase 2: Installing Visual Studio .NET IPhase 3: Checking for service releases 153_VBnet_TOC 8/16/01 1:12 PM Page xvi
1.引言 几乎所有的Web项目开发都需要客户端验证,尤其是JavaScript的使用,JS结合Html和CSS占据了网页展现市场,不管采用什么技术我们在网页看到的东西最终生成都是这些代码所表示含义。 Web应用如此广泛,其中客户端与服务端交互时所消耗的资源及响应时间,频繁的刷新页面使得人机交互体验极为不好,而对每个页面使用客户端处理技术无疑又加大项目开发周期,脚本调试及修改维护的工作量将占用大量的开发时间,验证控件须对每个控件的元素进行设置且会对页面整体的布局带来影响,占据着页面布局空间的位置,综合考虑及项目整体风格的统一等多种因素中,总得有个折中的考虑。ChkInputs.js应运而生,使用它不需要编写多少代码,只需对验证元素简单配置一下即可,使用方便,也不会影响页面的布局,并可以精确判断客户端输入的长度、必填、数据类型(整数型、浮点型、字母型、数字字母混合型)和下拉等,及对需要验证的控件分组验证等。同时提供许多常用的公共函数如类似C#中Trim()方法等。 使用ChkInputs.js,会将光标定位到验证不通过的控件上,若控件上有文本同时将其文本选中高亮度显示,不会刷新页面,只有当所有验证通过时才会将结果提交到后台处理,可以使用鼠标或纯键盘及相结合的方式来操作。 2.ChkInputs.js的使用: ChkInputs.js的使用极为方便,你可以直接将自定义属性像这样添加在Web页面, <input name="TextBox1" type="text" id="TextBox1" chinese="测试输入" maxsize="6" nullable="no" datatype="number" /> 也可以在后台代码里这样添加,如在.net下.aspx.cs代码里这样写: this.TextBox1.Attributes.Add("chinese", "测试输入");//控件名称 this.TextBox1.Attributes.Add("maxsize", "6");//控件接受的字符长度大小 this.TextBox1.Attributes.Add("nullable", "no");//不可为空,默认可为空 this.TextBox1.Attributes.Add("datatype", "number");//控件数据类型 两者代码是一样的,不过一般在后台代码(.cs)写好写,因为这样写有利于项目的维护修改。当页面的控件元素都设置好时,客户端代码通常只需这样写即可: 首先在页面head区域内定义一个这样的JS函数 <script language="javascript"> //例一,全部验证,比较常用,基本满足一般所有的验证功能 function CheckInfoAll() { return verifyAll(document.getElementById("form1")); } </script> 然后在需要验证的按钮上这样写 OnClientClick="return CheckInfoAll();" 或者使用onfocus ="rerurn CheckInfoAll();"或 onmousedown="rerurn CheckAll();" onkeydown="if(event.keyCode == 13){rerurn CheckAll();}" 后面的各种使用根据你的偏好选择使用。 除此之外,还可以指定验证及分组验证。指定验证如: return verifyInput(document.getElementById("TextBox1")); 分组验证同一个页面的元素最多可分六组(够用的了),各组之间互不影响,示例代码如下: //验证页面所属组group1="group1"的元素 function CheckAllGroup1() { return verifyAllByGroup1(document.getElementById("form1"),"group1") } 其它更多的使用详细代码可见附件示例代码所示。 3.ChkInputs的结构及原理: 这里先简要介绍一下文档对象模型(DOM)与树状结构,DOM可以让HTML元素与其属性,利用JS程序来控制。有两种方法将JS程序用于文档的元素:通过元素的名称和通过树状结构。这两个方法并非独立的,可能同时存在于相同的脚步中。 基本上对象是可以用脚步控制,或者可编程元素,拥有属性(Property)、事件(Event)以及方法(Method)。JS把所有网页元素、屏幕上可见的画面区域,以及浏览器的窗口都当成可编程的对象。所以,只要通过程序,你就可以控制这些对象的属性,执行其方法,以及捕捉这些事件等。 对象都有属性,有的属性就是对象本身。试想将人体当成对象,如果以分级的方式来看,人体对象有个躯干属性,而躯干有个心脏属性,心脏里还有心室属性。这些身体的零件都属于属性,而且全部都与人体对象之间有逻辑化的层次关系。 同样地,任何JavaScript这类面向对象程序语言的元素,也都是对象。这些对象都通过分级系统,作为主体的一部分。举例来说,浏览器窗口是一个对象,包含了几个文档对象,这些对象进而形成其他对象,依此类推,这个分级会变得很长。 由于面向对象的本质,JavaScript允许对象、对象的属性以及其事件都通过脚本来控制。也因为大部分网页浏览器都支持JavaScript,所以它是网页设计时最适合的客户端语言。ChkInputs.js就是通过JavaScript并结合DOM对象的自定义的属性而编写的。当使用时,ChkInputs.js会自动遍历DOM的元素,逐个检测直到所以验证完毕为止,由于事件触发在客户端响应非常及时,不会刷新页面。 该函数库提供许多函数库,就不一一列举了,这里举几个代表性的函数例子加以解释说明,先介绍一个频率用的最多的函数,如函数verifyAll,定义如下: function verifyAll(myform) {…………..} 参数myform指代验证的表单,可以比作验证树DOM的根,之后的JavaScript会遍历所有元素(elements),逐个检验,若没有设置验证则直接跳过,若有一个验证不通过,都不会将表单提交,并将光标定位到该处(focus()),若有文本同时高亮度选中该文本(select())。同样其他函数的原理也是类似。 另外,其他函数如数据长度的验证,是验证内容的实际字节的长度,即汉字两个字节英文及数字两个字节,判断依据ASCII值,计算机在设计字符存储的时候就是超过一个字节的ASCII字符都是以两个字节存放的。同时JavaScript提供了Scripting. FileSystemObject对象,GetFileSize(…)可直接取得待上传文件的字节大小,但也有限制就是客户端浏览须启用ActiveX插件,若没有启用时,会提示用户按步骤设置。CancelClientEvent()是使用事件冒泡阻止了事件的继续执行,同时设置返回值,最终成功阻止事件的继续往后执行,当在客户端触发一要回发的按钮事件是,想在程序里结束让其继续执行时,以往则不是很好处理,如Enter键,这里此方法则大显用武之地。 附有ChkInputs.js完整的源代码及实例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值