Asp. Net frontend page calls backend cs variable

Source: Internet
Author: User
Tags xsl file

1. Several similar markup symbols in ASP. NET: <% =... %> <% #... %> <% @ %> explanation and usage

A: <% #... %>: it is executed when the databind () method of the bound control is executed and used for data binding.

For example: <% # container. dataitem ("tit") %>

<% = %>: Called during program execution. The background variable value can be displayed.

For example:

*. In aspx: <% = aaa %>

*. CS: protected string AAA = "name ";

<%>: The Inline code block can be embedded with background code in the page file *. aspx or *. ascx.

For example:

<%

For (INT I = 0; I <100; I ++)

{

Reaponse. Write (I. tostring ());

}

%>

<% @ %> Is the front-end code import namespace on the *. ASPX page,

For example:

<% @ ImpORT namespace = "system. DaTa "%>

2. What types of data does the control receive?

A: controls that receive Bind, including DropDownList, DataList, DataGrid, and ListBox, which are mainly associated with ArrayList and Hashtable ), dataView (data view) and DataReader can be seated in the future without the error that the able is bundled :)

3. The data obtained by DataBind will be converted to another type by default as String?

DataBinder. EvAl (Container. DataItem, "converted type", "format ")

The last "format" is optional. Generally, you do not need to worry about it. Container. DataItem is a bundled data item. "Conversion Type" refers to Integer, String, Boolean.

4. Main namespace:

<% @ ImpOrt Namespace = "System. DaTa "%> used for data processing

<% @ ImpOrt Namespace = "System. DaTa. ADO "%> used when using ADO.net;

<% @ ImpOrt Namespace = "System. DaTa. SQL "%> dedicated to SQL Server databases

<% @ ImpOrt Namespace = "System. DaTa. XML "%> not used for processing XML

<% @ ImpOrt Namespace = "System. IO" %> used for File Processing

<% @ ImpORT namespace = "system. Web. util" %> used when sending emails

<% @ ImpORT namespace = "system. Text" %> used for Text Encoding

5. common attributes and methods of connections (sqlconection or adoconnection:

| Connectionstring: gets or sets the database connection statement.

| Connectiontimeout: gets or sets the maximum time for connecting 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: Get or set DSN. No stranger to everyone :)

| Password

| Userid: Get or set the login name

| State: gets the current join state.

| Open () Open the connection

| Close () Close the connection

| Clone (): clone a join. (Hehe, the sheep can connect or I 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. common methods and attributes of Command

| ActiveConnection

| Name of the SQL statement or stored procedure (StoredProcedure) executed by CommandText

| Maximum CommandTimeout execution time

| CommandType Command operation types (StoredProcedure, Text, TableDirect). The default value is Text.

| Parameters

| Execute () Execute SQL statements or stored procedures

| ExecuteNonQuery () is the same as above. The difference is that the record set is not returned.

| 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. You can open or close a database in either of the following ways:

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"] = "Zhou Xun ";

Dr ["ReMark"] = "100 ";

Dr ["Comment"] = "Beautiful mm ";

MyDataSet. Tables. Rows. Add (dr );

B. modify data

MyDataSet. Tables ["UserList"]. Rows [0] ["UserName"] = "Flying knife ";

C. delete data

MyDataSet. Tables ["UserList"], Rows [0]. Delete ();

D. Restore data

If (MyDataSet. HasErrors)

{

MyDataSet. RejectChanges ();

}

E. Check whether DataSet has been modified.

If (MyDataSet. HasChanges)

{

// Save the code

} Else {

// Because there is no change, you do not need to save it to save time

}

F. update the database

MyComm. Update (MyDataSet); // Update all tables in the database

MyComm. Update (MyDataSet, "UserList"); // Update a table

9. The DataGrid provides the paging function.

AllowPaging = "True" // indicates that pagination is allowed. With it, we can paging.

PageSize = "5" // specifies the number of records displayed on each page. If this parameter is not set, 10 records are displayed by default.

PagerStyle-HorizontalAlign = "Right" // specifies the position of the split display. The default value is Left.

PagerStyle-NextPageText = "next page" // change <> to the string of the previous page and next page.

PagerStyle-PrevPageText = "Previous Page"

PagerStyle-Mode = "NumericPages" // change <> to 123 Numeric Display

10. display the total number of pages and the current report is the page number

Current page: <% = DataGrid1.CurrentPageIndex + 1%>

Total number of pages: <% = DataGrid1.PageCount %>

11. Personalized Paging

Programmer base camp "close access to ASP. Net (14)" with complete code

12. You need to reset the page to a valid status.

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. Repeater, DataList, and DataGrid Control usage"

These controls simplify several common Web application solutions, including reports, shopping carts, product lists, and queries.

Result and navigation menu. Repeater is the only control that allows HTML fragments to exist in its template.

16. Differences between Server. Execute ("another. aspx") and Server. Transfer ("another. aspx:

Execute transfers the execution from the current page to the specified page and returns the execution to the current page.

Transfer completely transfers the execution to the specified page

17. The XML file can either have its own architecture or exist in the *. xsl file, but the information must be specified in the root node of the xml file through the xmlns attribute, as shown below:

18. Reading 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. RegularExpressionValidator

Symbol Meaning

^ Specify the start of the check

$ Specify the end Of the check

[] Check whether the input value matches one of the characters in square brackets.

\ W allows input of any value

\ D {} "\ d" indicates that the input value is a 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 checked

Example: email format (with @ number and ended with. com/. net/. org/. edu)

Validationexpression = "^ [\ w-] + @ [\ w-] + \. (com | net | org | edu) $"

20. Important statements for data operations in the DataGrid Control:

Attribute: 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]; // Number of Primary keys of the row to be updated (assign 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; // assign the modified row value to the parameter

 

21. Custom Controls:

A. User Control (the same as creating a page in ASP)

(I ). create a page, drag the control, and set properties/methods. the @ Control command 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 control prefix, such as ASP in ASP: TextBox.

// TagName is used to specify the name of the custom control.

// Src specifies the Control File Source

Body:

B. Use C # To create a custom control

(I). Create a pure code file, inherit the Control class of the base class, and save it as *. cs, such as a. cs.

(II) Compile the code to generate the Assembly: csc/t: library/r: System. dll, System. Web. Dll a. cs

// The library tells C # That the compiler generates an assembly.

/// R: System. dll System. Web. Dll tells C # That the compiler references the specified assembly.

(III). Place the generated dll file in the bin directory.

(IV). Usage: <% @ Register TagPrefix = "Mine" Namespace = "MyOwnControls" Assembly = "a" %>

22. Precautions for composite controls:

Public class MyCompositin: Control, INamingContainer // INamingContainer: if there are multiple Control instances on the page, this interface can have a unique identifier for each {}/instance.

This. EnsureChildControls (); // displays the child controls of the composite control on the page. this method checks whether the server control contains child controls.

CreateChildControls

23. When will Button/LinkButton/ImageButton/HyperLink be used?

1. The buttons 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 the data on the server.

24. Tracking and debugging

Tracking:

1. Page-level tracking: The following Page commands are included 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"); // It is the same as Trace. Write, but the font is red.

Check whether a trail is used

Example: if (Trace. IsEnabled) {Trace. Warn ("enabled Trace ")}

2. Application-level tracking: in the section of the Web. config file

25. Set cache:

1. Output cache:

I. Page settings: Add <% @ OutputCache Duration = "120" VaryByParam = "none" %> to the beginning of the page to be cached.

Note: The output content remains unchanged within two minutes after the page is requested.

II. Programming Method settings:

It mainly uses methods in the System. Web. HttpCachePolicy class.

(1). Response. Cache. SetExpires (DateTime. Now. AddSeconds (120); // you must specify the expiration time in this method. For example, the current sentence is two minutes.

(2). Response. Cache. SetExpires (DateTime. Now. AddSeconds (120 ));

Response. Cache. SetSlidingExpiration (true); // "adjustable expiration", mainly used in scenarios where the access volume is large but the access volume is balanced subsequently

Function: Set the cache expiration time In the first sentence, and enable the sliding expiration (adjustable expiration) in the second line ).

2. Data Cache:

(1). DataView mySource; (2). assign a value to mySource;

(3). Cache ["myCache"] = mySource; (4). mySource = (DataView) Cache ["myCache"]

26. Deployment: copy the statement directly to the product server: XCOPY // XOPY only accepts the physical path, not the virtual path

26. Custom page 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 ("[page {0}]", l. Text );
}
}

}

}

2. Reference: zhangzs8896 (xiao'er)
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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.