ASP.Net foreground calls the methods of the background variables

  • 2020-05-10 17:56:36
  • OfStack

Net foreground calls the background variable
1. Several similar symbols in Asp. Net: < %=...% > < %#... % > < % % > < %@ % > Explanation and usage
A: < %#... % > : is executed when the bound control DataBind() method is executed for data binding
Such as: < %# Container.DataItem("tit") % >
< %= % > : is called while the program is executing, and the value of the background variable can be displayed
Such as:
*. aspx: < %= aaa % >
*.cs: protected string aaa=" name ";
< % % > : the inline code block can embed background code in the page file *.aspx or *.ascx
Such as:
< %
for(int i=0;i < 100;i++)
{
Reaponse.Write(i.ToString());
}
% >
< %@ % > Is to import the namespace into the foreground code on the *.aspx page,
Such as:
< %@ Import namespace="System.Data"% >
2. What type of data does the control receive?
Answer: receiving Bind controls, 1 have DropDownList, DataList, DataGrid, ListBox nature of these sets of controls, and bound mainly ArrayList (array), Hashtable (rare table), DataView (data view), DataReader these four, later we can accordingly, will appear DataTable tied a mistake:)
3.DataBind, the data obtained, the system will default to String, how to convert to other types?
DataBinder.Eval (Container.DataItem," type of conversion "," format ")
Container.DataItem is the data item that is bundled. "conversion type" refers to Integer,String,Boolean and so on.
4. Main namespaces:
< % @ Import Namespace="System.Data" % > Used when processing data
< % @ Import Namespace="System.Data.ADO" % > Using ADO. net; Used when
< % @ Import Namespace="System.Data.SQL" % > SQL Server database exclusive
< % @ Import Namespace="System.Data.XML" % > You don't have to look at XML
< % @ Import Namespace="System.IO" % > Used when working with files
< % @ Import Namespace="System.Web.Util" % > You'll use it when you send an email
< % @ Import Namespace="System.Text" % > Text encoding
5. Common attributes and methods of Connections(SQLConection or ADOConnection) :
| ConnectionString gets or sets a statement that connects to a database
The maximum time that | ConnectionTimeout can get or set a database connection is also the timeout
| DataBase gets or sets the database name to open on the database server
| DataSource gets or sets DSN :)
| Password gets or sets the password
| UserID gets or sets the login name
| State gets the current state of the connection
| Open() opens the join
| Close() closes the connection
| Clone() clones a join. (hehe, the sheep can Connection I can also)
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. Common methods and properties of Command
| ActiveConnection gets or sets the join Connections
The name of the SQL statement or stored procedure (StoredProcedure) executed by | CommandText
Maximum time for | CommandTimeout execution
| CommandType Command operation types (StoredProcedure,Text,TableDirect), default Text
| Parameters is used when manipulating the storage process
| Execute() executes SQL statements or stores procedures
| ExecuteNonQuery() ibid. The difference is that no recordset is returned
| Clone() clones 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 ways 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 1 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 knife ";
c. Delete data
MyDataSet.Tables["UserList"],Rows[0].Delete();
d. Restore data
if(MyDataSet.HasErrors)
{
MyDataSet.RejectChanges();
}
e. Detect changes to DataSet
if(MyDataSet.HasChanges)
{
// save the code
}else{
// since there are no changes, no need to save to save time
}
f. Update database
MyComm. Update (MyDataSet); // update all the tables in the database
MyComm. Update (MyDataSet, "UserList"); // update a table
9.DataGrid implements paging function
AllowPaging="True" // means allow paging, this is the main one. With it, we can page.
PageSize="5" // is the number of records to be displayed per page. If not, 10 records will be displayed by default.
PagerStyle-HorizontalAlign="Right" // is the location of the specified faceted display. The default is Left
PagerStyle-NextPageText=" next 1 page "// put < > Change to the previous page and the next page string
PagerStyle-PrevPageText=" previous 1 page"
PagerStyle - Mode = "NumericPages" / / < > Change it to 123
10. Show how many pages 1 has and what page the report is currently on
The current page is: < %=DataGrid1.CurrentPageIndex+1% >
The total pages are: < %=DataGrid1.PageCount% >
11. Personalize pagination
ASP.Net(14) has the complete code
Reset the page to a valid state
IValidator val;
foreach(val in Validators)
{
Val.IsValid = true;
}
13. Reexecute the entire validation sequence
IValidator val;
foreach(val in Validators)
{
Val.Validate();
}
14. Disable client validation
< %@ Page Language="c#" clienttarget=downlevel % >
15. Use of Repeater, DataList and DataGrid controls ""
These controls simplify several common Web application scenarios, including reports, shopping carts, product lists, and queries
Results and navigation menus. Repeater is the only control that 1 allows an HTML fragment to exist in its template.
16. Server. Execute(" another. aspx") and Server. Transfer(" another. aspx")
Execute moves from the current page to the specified page and returns the execution to the current page
Transfer is the full transfer of execution to the specified page
17. The schema can exist in the XML file or in the *.xsl file, but this information must be specified in the root node of the xml document through the xmlns attribute, as shown below:
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
Symbolic meaning
^ specify where the check begins
$specifies the end of the check
[] checks that the input value matches the character 1 in the square bracket
\W allows you to enter any value
\d{} "\d" specifies that the input value is 1 number, and {} indicates the number of occurrences of the specified data type
+ indicates that one or more elements will be added to the expression being examined
Example: E-mail format (with @ #, and. com /. net /. org /. edu end)
validationexpression="^[\w-]+@[\w-]+\.(com|net|org|edu)$"
20. Important statements for data manipulation in DataGrid control:
Property :DataKeyField="userid" // if userid is the primary key of the table, the value of this field cannot be updated to the database. It is better to set the primary key of the table as the primary key of DataGrid
"@ userid" SqlCommand. Parameters [] Value = dg. DataKeys [(int) e. Item. ItemIndex]; // retrieves the number of primary keys (1 parameter assigned to the command by the primary key value of the currently selected row) of the row to be updated
"@ fname" SqlCommand. Parameters [] Value = ((TextBox) e. Item. Cells [2]. Controls [0]). Text; // assign the modified row value to the parameter
21. Custom control:
a. User controls (ASP create page 1 sample)
(I). Create a page, drag in the control, and set properties/methods. < % @Control Language="C#" Debug="True" % > The @Control directive to define 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 for the control, like ASP: ASP in TextBox
//TagName is used to specify the name of the custom control
//Src specifies the source of the control file
Body:
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). To compile the code generator set: csc/t: library/r: System. dll, System. Web. Dll a. cs
//library tells the C# compiler to generate the 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 control:
public class MyCompositin:Control,INamingContainer //INamingContainer: if there are multiple instances of this control on the page, this junction can give each {} // instance a unique 1 flag
this. EnsureChildControls (); // represents rendering the children of the composite control to the page. This method checks whether the server control contains the children
CreateChildControls
23. Button/LinkButton/ImageButton/HyperLink when to use?
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 or access data on a server
24. Trace debugging
Tracking:
1. Page level tracking: 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 display ");
Trace.Warn (" here is the string to display "); // is the same as Trace.Write, except the font is red
Check if trace is used
Example: if(Trace.IsEnabled) {Trace.Warn (" trace enabled ")}
2. Application level tracking: in the section of the Web.config file
25. Setting cache:
1. Output cache:
I. Page Settings: will < %@ OutputCache Duration="120" VaryByParam="none" % > Add to the beginning of the page you want to cache
Note: the output remains the same for the next two minutes after the page is requested
II. Programming mode Settings:
The main method used is under class System.Web.HttpCachePolicy
(1). Response. Cache. SetExpires (DateTime. Now. AddSeconds (120)); // in this method you must specify an expiration time of, say, two minutes in this language // sentence
(2). Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));
Response. Cache. SetSlidingExpiration (true); //" adjustable expiration "is mainly used for those situations where the volume of traffic is large at the beginning, but then the volume is balanced
Function: the first sentence sets the cache expiration time, and the second line opens 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 production server copy statement: XCOPY //XOPY only accepts physical paths, not virtual paths
26. Custom paging button
1.
 
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("[ The first {0} page ]", l.Text); 
} 
} 
} 
} 

2. Quote :zhangzs8896(minor 2)
 
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; 
} 
} 
} 
} 

Related articles: