1. The difference between <%=...%> and <%#... %>:
Answer: <%=...%> is called when the program is executed, and <%#... %> is called after the DataBind() method.
2. What types of data does the control receive?
Answer: Controls that receive Bind generally include collection controls such as DropDownList, DataList, DataGrid, and ListBox. The main ones that are bundled are ArrayList, Hashtable, DataView, and DataReader. , we can get it right in the future, and there will be no error that the DataTable is bound:)
3. DataBind, the system will default the obtained data to String, how to convert it to other types?
DataBinder.Eval(Container.DataItem,"conversion type","format")
The last "format" is optional, and generally you don't need to worry about it. Container.DataItem is a bundled data item, and "conversion type" refers to things like Integer, String, and Boolean.
4. Main namespace:
<% @ Import Namespace="System.Data" %> Used when processing data
<% @ Import Namespace="System.Data.ADO" % > Used when using ADO.net;
<% @ Import Namespace="System.Data.SQL" %> SQL Server database only
<% @ Import Namespace="System.Data.XML" %> No need to look at what is used to process XML
<% @ Import Namespace="System.IO" %> Used when processing files
<% @ Import Namespace="System.Web.Util" %> Everyone will use it when sending emails
<% @ Import Namespace="System.Text" %> Common properties and methods of 5.Connections (SQLConection or ADOConnection) are used when encoding text
:
| ConnectionString Gets or sets the statement to connect to the database
| ConnectionTimeout gets or sets the maximum time to connect to the database, which is also the timeout time
| DataBase gets or sets the name of the database to be opened on the database server
| DataSource obtains or sets DSN, everyone is familiar with it:)
| Password Get or set password
| UserID gets or sets the login name
| State gets the status of the current connection
| Open() opens the connection
| Close() closes the connection
| Clone() Clone a connection. (Haha, sheep can connect and so can I)
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. Commonly used methods and properties of Command
| ActiveConnection Gets or sets Connections
| CommandText executes the SQL statement or stored procedure (StoredProcedure) name
| CommandTimeout The maximum execution time
| CommandType There are three types of Command operations (StoredProcedure, Text, TableDirect), the default is Text
| Parameters used when operating stored procedures
| Execute() executes SQL statements or stored procedures
| ExecuteNonQuery() Same as above, the difference is that it does not return a record set
| Clone() Clone Command
Example:
string mySelectQuery = "SELECT * FROM Categories ORDER BY CategoryID";
stringmyConnectString="userid=sa;password=;database=northwind;server=mySQLServer";
SQLCommand myCommand = new SQLCommand(mySelectQuery);
myCommand.ActiveConnection = new SQLConnection(myConnectString);
myCommand.CommandTimeout = 15;
myCommand.CommandType = CommandType.Text;< /FONT >
7. Two methods to open and close the database:
1.MyConnection.Open(); //Open the connection
MyConnection.Close();
2.MyCommand.ActiveConnection.Open();
MyCommand.ActiveConnection.Close()
8. Use DataSet to add, modify, and delete data in the database
a.Add data
DataRow dr=MyDataSet.Tables["UserList"].NewRow();
dr["UserName"] = "Weekly News";
dr["ReMark"] = "100";
dr["Comment"] = "Beautiful MM";
MyDataSet.Tables.Rows.Add(dr);
b. Modify data
MyDataSet.Tables["UserList"].Rows[0]["UserName"]="Brother Flying Knife";
c. Delete data
MyDataSet.Tables["UserList"],Rows[0].Delete();
d.Restore data
if(MyDataSet.HasErrors)
{
MyDataSet.RejectChanges();
}
e. Detect whether the DataSet has been changed
if(MyDataSet.HasChanges)
{
//save code
}else{
//Because there are no changes, there is no need to save to save time.
}
f. Update database
MyComm.Update(MyDataSet); //Update all tables in the database
MyComm.Update(MyDataSet,"UserList"); //Update a table
9.DataGrid implements paging function
AllowPaging="True" //Refers to allowing paging, this is the most important. With it, we can paginate.
PageSize="5" //Specifies the number of records displayed on each page. If not written, it will default to 10.
PagerStyle-HorizontalAlign="Right" //Specifies the positioning of faceted display, the default is Left
PagerStyle-NextPageText="Next page" //Change <> to the previous page and next page strings
PagerStyle-PrevPageText="Previous page"
PagerStyle-Mode="NumericPages" //Change <> to 123 digital display
10. Display how many pages there are in total and what page the report is currently on
The current page is: <font color=red><%=DataGrid1.CurrentPageIndex+1%></font><br>
The total number of pages is: <font color=red><%=DataGrid1.PageCount%></font><br>
11.Personalized paging
Programmer's Basecamp's "Close Contact ASP.Net (14)" 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. Disable client verification
<%@ Page Language="c#" clienttarget=downlevel %>
15.Usage of Repeater, DataList and DataGrid controls"
These controls can simplify several common web application scenarios, including reports, shopping carts, product lists, queries
Results and navigation menu. Repeater is the only control that allows HTML fragments in its template.
16. The difference between Server.Execute("another.aspx") and Server.Transfer("another.aspx"):
Execute transfers from the current page to the specified page and returns execution to the current page
Transfer is to completely transfer the execution to the specified page
17. The XML file can have its own schema, or it can exist in the *.xsl file, but the information must be specified in the root node of the xml document through the xmlns attribute, as shown below:
<rootelement xmlns="x-schema:scheduledSchema.xsl">
18. Reading of XML files
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
Symbol Meaning
^ Specify where to start the check
$ specifies the end of the check
[] Checks whether the entered value matches one of the characters in square brackets
W allows any value to be entered
d{} "d" specifies that the input value 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: Email format (has @ sign and ends with .com/.net/.org/.edu)
validationexpression="^[w-]+@[w-]+.(com|net|org|edu)$"
20. Important statements for data operations in the DataGrid control:
Property: DataKeyField="userid" //Set userid as the primary key of the table. The value of this field cannot be updated to the database. It is best to set the primary key of the table as the primary key of the DataGrid.
SqlCommand.Parameters["@userid"].Value=dg.DataKeys[(int)e.Item.ItemIndex]; //Retrieve the primary key of the row to be updated (assign the primary key value of the currently selected row to the command's a parameter
SqlCommand.Parameters["@fname"].Value=((TextBox)e.Item.Cells[2].Controls[0]).Text; //Assign the modified row value to the parameter
21. Custom controls:
a. User control (same as ASP creation page)
(I). Create a page, drag in the control, and set properties/methods. The @Control directive in <% @Control Language="C#" Debug="True" %> to define this page will contain the control code
(II) Save as *.ascx file, such as a.ascx.
(III).Use: Header< %@Register Tagprefix="MyFirstControl" TagName="MyLbl" Src="a.axcs" %>
//Tagprefix is the prefix of the control, like ASP:TextBox in ASP
//TagName is used to specify the name of the custom control
//Src specifies the control file source
Body:<MyFirstControl:MyLbl runat="Server" id="AllMine" MyText="Successful" />
b. Create custom controls using C#
(I). Create a pure code file, inherit the base class Control, and save it as *.cs, such as a.cs.
(II). Compile the code to generate an assembly: csc /t:library /r:System.dll,System.Web.Dll a.cs
//library tells the C# compiler to generate an assembly
// /r:System.dll System.Web.Dll tells the C# compiler to reference the specified assembly
(III). Place the generated dll file in the bin directory
(IV).Use: <% @Register TagPrefix="Mine" Namespace="MyOwnControls" Assembly="a" %>
22. Precautions for composite controls:
public class MyCompositin:Control,INamingContainer //INamingContainer: If there are multiple instances of this control on the page, this interface can give each {} instance a unique flag
this.EnsureChildControls();//Indicates that the composite control will
beAll child controls are rendered to the page. This method checks whether the server control contains child controls
CreateChildControls
23.When are Button/LinkButton/ImageButton/HyperLink used?
1.Button and ImageButton are used to pass data back to the server.
2.Hyperlink is used to navigate between pages
3.LinkButton is used to save data to the server or access data on the server
24. Tracking and debugging
track:
1. Page level tracing: Include the following page instructions at the beginning of the page <%@ Page Trace="True" TraceMode="SortByCategory/SortByTime" %>
Custom message:
Trace.Write("Here is the string to be displayed");
Trace.Warn("Here is the string to be displayed"); //Same as Trace.Write, except that the font is red
Check if tracking is used
Example: if(Trace.IsEnabled) { Trace.Warn("Tracing is enabled")}
2. Application level tracing: <trace enabled="true" pageOutput="true"/> in the <System.Web> section of the Web.config file
25. Set up cache:
1.Output caching:
I. Page settings: Add <%@ OutputCache Duration="120" VaryByParam="none" %> to the beginning of the page that needs to be cached
Note: The output content remains unchanged within the last two minutes of requesting this page.
II. Programmatic settings:
Mainly use methods under the class System.Web.HttpCachePolicy class
(1). Response.Cache.SetExpires(DateTime.Now.AddSeconds(120)); //The expiration time must be specified in this method, such as this //sentence is two minutes
(2). Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));
Response.Cache.SetSlidingExpiration(true); //"Adjustable expiration" is mainly used for situations where the number of visits is large at first, but then the number of visits //is balanced
Function: The first line sets the cache expiration time, and the second line turns on sliding expiration (adjustable expiration).
2. Data cache:
(1).DataView mySource; (2).Assign value to mySource;
(3).Cache["myCache"]=mySource; (4).mySource=(DataView)Cache["myCache"]
26. Deployment: Copy directly to the product server to copy the statement: XCOPY <source_path> <destination_path> //XOPY only accepts physical paths, not virtual paths