NET foreground call background variable
Several similar notation symbols in 1.asp.net: <%=...%><% # ...%><%%><%@ interpretation and usage
A: <% # ...%>: is executed when the bound control DataBind () method executes, for data binding
such as: <% # Container.DataItem ("tit")%>
<%=%>: Called when the program executes, can display the background variable value
Such as:
*.aspx: <%= AAA%>
*.cs: Protected string aaa= "name";
<%%>: Inline code blocks can be embedded in the page file *.aspx or *.ascx files inside the background code
Such as:
<%
for (int i=0;i<100;i++)
{
Reaponse.write (i.ToString ());
}
%>
<%@%> is to import namespaces in the *.aspx page foreground code,
Such as:
<%@ Import namespace= "System.Data"%>
2. What type of data does the control receive?
A: Receive bind control, generally have dropdownlist,datalist,datagrid,listbox these set properties of the control, while the main bundle is ArrayList (array), Hashtable (HA dilute table), DataView ( Data View), DataReader These four, we will be able to take a seat, there will be no DataTable bundled error:
3.DataBind, the data obtained, the system will assume its default string, how to convert to other types?
DataBinder.Eval (Container.DataItem, "type of conversion", "format")
The last "format" is optional, generally do not have to care about him, Container.DataItem is a bundle of data items, "conversion type" refers to the Integer,string,boolean this kind of thing.
4. Main namespaces:
<% @ Import namespace= "System.Data"%> used when processing data
<% @ Import namespace= "System.Data.ADO"% > Use ado.net; When you use the
<% @ Import namespace= "System.Data.SQL"%> SQL Server database dedicated
<% @ Import namespace= "System.Data.XML"%> without looking at processing XML
<% @ Import namespace= "System.IO"%> When processing files
<% @ Import namespace= "System.Web.Util"%> email when you use
<% @ Import namespace= "System.Text"%> text encoding
Common properties and methods for 5.Connections (Sqlconection or adoconnection):
| ConnectionString Gets or sets the statement that links the database
| ConnectionTimeout Gets or sets the maximum time to connect to the database, and also the timeout time
| DB Gets or sets the name of the database to open on the database server
| DataSource Get or Set DSN, we are not unfamiliar bar:
| Password get or set a password
| UserID Get or Set login name
| State gets the status of the current join
| Open () opens the join
| Close () off join
| Clone () clones a join. (Oh, sheep can connection I also can)
Example:
SqlConnection myconnection = new SqlConnection ();
Myconnection.datasource = "MySQLServer";
Myconnection.password = "";
Myconnection.userid = "sa";
Myconnection.connectiontimeout = 30;
Myconnection.open ();
Myconnection.database = "Northwind";
Myconnection.isolationlevel = isolationlevel.readcommitted
6.Command Common methods and properties
| ActiveConnection Gets or sets the join connections
| SQL statement or stored procedure (storedprocedure) name executed by CommandText
| CommandTimeout the maximum time to execute
| CommandType command operation type (storedprocedure,text,tabledirect) three, default Text
| Use when Parameters operation stored procedure
| Execute () executes the SQL statement or stored procedure
| ExecuteNonQuery () ditto, except that the recordset is not returned
| Clone () Cloning command
Example:
String myselectquery = "SELECT * from Categories ORDER by CategoryID";
stringmyconnectstring= "userid=sa;password=;d atabase=northwind;server=mysqlserver";
SQLCommand mycommand = new SQLCommand (mySelectQuery);
Mycommand.activeconnection = new SqlConnection (myconnectstring);
Mycommand.commandtimeout = 15;
myCommand.CommandType = commandtype.text;</font >
7. Open and close the database in two ways:
1.myconnection.open (); Open Join
Myconnection.close ();
2.mycommand.activeconnection.open ();
MyCommand.ActiveConnection.Close ()
8. Use DataSet to add, modify, delete a data in the database
A. Adding data
DataRow dr=mydataset.tables["UserList"]. NewRow ();
dr["UserName"] = "Zhou Xun";
dr["remark"] = "100";
dr["Comment"] = "beautiful mm";
MYDATASET.TABLES.ROWS.ADD (DR);
B. Modifying data
mydataset.tables["UserList"]. rows[0]["UserName"]= "flying brother";
C. Deleting data
mydataset.tables["UserList"],rows[0]. Delete ();
D. Recovery of data
if (mydataset.haserrors)
{
Mydataset.rejectchanges ();
}
E. Detection of DataSet changes
if (mydataset.haschanges)
{
Save Code
}else{
Because there is no change, so don't save it to save time
}
F. Updating the database
Mycomm.update (myDataSet); Update all tables in the database
Mycomm.update (myDataSet, "userlist"); Update a table
9.DataGrid Implementation Paging function
allowpaging= "True"//refers to allowing paging, which is the most important. With it, we can be divided into pages.
Pagesize= "5"//is to specify the number of records to display per page, and if not, the default is 10.
Pagerstyle-horizontalalign= "Right"//is the specified faceted display positioning, the default is left
Pagerstyle-nextpagetext= "Next"//<> change to previous page and next string
pagerstyle-prevpagetext= "Previous Page"
Pagerstyle-mode= "NumericPages"//<> change to 123 digital display
10. Show how many pages there are, and report the current page
The current page is:<%=datagrid1.currentpageindex+1%>
The total number of pages is:<%=datagrid1.pagecount%>
11. Personalize pagination
The "Intimate contact asp.net (14)" of the programmer's base has complete code
12. To reset the page to a valid state
IValidator Val;
foreach (Val in validators)
{
Val.isvalid = true;
}
13. Re-execute the entire verification sequence
IValidator Val;
foreach (Val in validators)
{
Val.validate ();
}
14. Disabling Client Authentication
<%@ Page language= "C #" Clienttarget=downlevel%>
15.Repeater, DataList and DataGrid control uses "
These controls can simplify several common WEB application scenarios, including reports, shopping carts, product lists, query
Results and navigation menus. Repeater is the only control that allows HTML fragments to exist in its templates.
difference between 16.server.execute ("another.aspx") and Server.Transfer ("Another.aspx"):
Execute is transferred from the current page to the specified page and the execution is returned to the current page
Transfer is the complete transfer of execution to the specified page
The 17.XML file can have a schema of its own, or it can exist in the *.xsl file, but it must be specified in the root node of the XML document through the xmlns attribute, as follows:
18.XML file Read
FileStream myfs=new FileStream (Server.MapPath ("Xmldtagrid.xml"), FileMode.Open,FileAccess.Read);
StreamReader myreader=new StreamReader (MYFS);
DataSet myds=new DataSet ();
myDS. READXML (myreader);
19. Regular expression Control RegularExpressionValidator
Symbolic meaning
^ Specify inspection at start
$ Specify the end of the check
[] Check if the value entered matches one of the characters in the square bracket
\w allow any value to be entered
\d{} "\d" specifies that the value entered is a number, {} Indicates the number of occurrences of the specified data type
+ indicates that one or more elements will be added to the expression being checked
Example: e-mail format (with the @ sign and ending with. com/.net/.org/.edu)
Validationexpression= "^[\w-]+@[\w-]+\. (com|net|org|edu) $ "
Data manipulation important statements in 20.DataGrid controls:
Properties: datakeyfield= "userid"//Set UserID as the primary key of the table, cannot update the value of the field to the database, preferably set the primary key of the table to the DataGrid's primary key
sqlcommand.parameters["@userid"]. VALUE=DG. datakeys[(int) e.item.itemindex]; Retrieves the primary key of the row to be updated (assigns the primary key value of the currently selected row to a parameter of the command)
sqlcommand.parameters["@fname"]. Value= ((TextBox) e.item.cells[2]. Controls[0]). Text; To assign a modified row value to a parameter
21. Custom CONTROLS:
A. User controls (as ASP creates pages)
(I). Create pages, drag controls, set properties/methods. <% @Control language= the @control directive in the "C #" debug= "True"%> defines that this page will contain control code
(II) Save as a *.ascx file, such as A.ascx.
(III). Use: Head <% @Register tagprefix= "Myfirstcontrol" tagname= "Mylbl" src= "A.axcs"%>
TagPrefix is the prefix of the control, like the ASP in Asp:textbox
TagName is used to specify the name of a custom control
SRC Specifies the control file source
Body:
B. Creating a custom control using C #
(I). Create a plain code file that inherits the base class control and is saved as a *.cs, such as A.cs.
(II). Compiling code to build an assembly: Csc/t:library/r:system.dll,system.web.dll A.cs
The library tells the C # compiler to generate assemblies
/r:system.dll System.Web.Dll tells the C # compiler to reference the specified assembly
(III). Put the build DLL file in the bin directory
(IV). Use: <% @Register tagprefix= "Mine" namespace= "Myowncontrols" assembly= "a"%>
22. Composite Control Considerations:
public class Mycompositin:control,inamingcontainer//inamingcontainer: If you have more than one instance of this control on the page, this node can have a unique flag for each {}//instance
This. EnsureChildControls ();//indicates that the child controls for the composite control are rendered to the page, which checks whether the server control contains child controls
CreateChildControls
When will 23.button/linkbutton/imagebutton/hyperlink be used?
1.Button and ImageButton are used to pass data back to the server.
2.Hyperlink for navigating between pages
3.LinkButton is used to save data to the server or to access data on the server
24. Track and Debug
Tracking:
1. Page-level tracking: Include the following page directives at the beginning of the page <%@ page trace= "True" tracemode= "Sortbycategory/sortbytime"%>
Custom message:
Trace.Write ("Here is the string to display");
Trace.Warn ("Here is the string to display"); Same as Trace.Write, except the font is red
Check if tracking is used
Example: if (trace.isenabled) {Trace.Warn ("tracing Enabled")}
2. Application-level tracking: In the section of the Web.config file
25. Set Cache:
1. Output Caching:
I. Page Setup: Add <%@ OutputCache duration= "%>" varybyparam= "none" to the beginning of the cached page
Note: The output is unchanged within two minutes of requesting the page
Ii. Programming Method Setting:
The main use of the method under Class System.Web.HttpCachePolicy class
(1). Response.Cache.SetExpires (DateTime.Now.AddSeconds (120)); The expiration time must be specified in this method, such as the text//sentence of two minutes
(2). Response.Cache.SetExpires (DateTime.Now.AddSeconds (120));
Response.Cache.SetSlidingExpiration (TRUE); "Adjustable expiration", mainly for those with a large number of initial visits, but subsequent access//volume balances
Function: The first sentence sets the cache expiration time and the second line opens the sliding expiration (adjustable expiration).
2. Data caching:
(1). DataView MySource; (2). assigning value to MySource;
(3). cache["Mycache"]=mysource; (4). mysource= (DataView) cache["Mycache"]
26. Deployment: Copy the statement directly to the product server: XCOPY//xopy accepts only physical paths and does not accept virtual paths
26. Customize the page-splitting button
1.
Copy Code code as follows:
protected void ItemCreated (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
System.Web.UI.WebControls.ListItemType elemtype = E.item.itemtype;
if (elemtype = = System.Web.UI.WebControls.ListItemType.Pager)
{
TableCell pager = (TableCell) e.item.controls[0];
for (int i=0; I {
Object o = pager. Controls[i];
If (O is LinkButton)
{
LinkButton h = (LinkButton) o;
H.text = "" + H.text + "";
}
Else
{
Label L = (label) o;
L.text = String.Format ("[{0} page]", l.text);
}
}
}
}
2. Reference: zhangzs8896 (small two)
Copy Code code as follows:
private void Mydatagrid_itemcreated (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
ListItemType Lit_item=e.item.itemtype;
TableCell tc_item= (TableCell) e.item.controls[0];
if (Lit_item==listitemtype.pager)
{
for (int i=0;i {
Object Obj_item=tc_item. Controls[i];
if (Obj_item is LinkButton)
{
LinkButton lbn_item= (LinkButton) Obj_item;
Lbn_item. Text=lbn_item. Text;
Lbn_item. font.size=10;
Lbn_item. Forecolor=color.fromname ("#666666");
Lbn_item. Attributes.Add ("onmouseover", "Currentcolor=this.style.color;this.style.color= ' #14AC05");
Lbn_item. Attributes.Add ("onmouseout", "This.style.color=currentcolor");
}
Else
{
Label lbl_item= (label) Obj_item;
Lbl_item. Forecolor=color.blue;
Lbl_item. Font.bold=true;
Lbl_item. Font.underline=true;
Lbl_item. text= "" + Lbl_item. Text + "";
Lbl_item. font.size=10;
}
}
}
}