. Net learning notes-Details

Source: Internet
Author: User

This article is a companion to ASP. NET programming skills (http://blog.csdn.net/zhouwen/archive/2010/09/16/5889330.aspx), recording. Net learning notes-details! Sometimes, Details determine success or failure!

(1) how to determine whether two string objects point to the same reference?

String S1 = "AA ";
String S2 = "AA ";
MessageBox. Show (object. referenceequals (S1, S2). tostring (); // true

Char [] CH = {'A', 'A '};
String S1 = new string (CH );
String S2 = "AA ";
MessageBox. Show (object. referenceequals (S1, S2). tostring (); // false
(2) obtain the local IP address.
Public static IPaddress [] getlocalhostipv4addresses ()
{
String localhostname = DNS. gethostname ();
Iphostentry host = DNS. gethostentry (localhostname );
List <IPaddress> addresses = new list <IPaddress> ();
Foreach (IPaddress IP in host. Addresslist)
{
If (IP. addressfamily = addressfamily. InterNetwork)
Addresses. Add (IP );
}
Return addresses. toarray ();
}

(3) how to convert form coordinates into screen coordinates?
Private void form4_mousemove (Object sender, mouseeventargs E)
{
Textbox1.text = string. Format ("X: {0}, Y: {1}", E. X, E. y );
Point P = new point (E. X, E. y );
P = This. pointtoscreen (p); // convert the form coordinates into screen coordinates
Textbox2.text = string. Format ("X: {0}, Y: {1}", p. x, P. y );
P = This. pointtoclient (P );
Textbox3.text = string. Format ("X: {0}, Y: {1}", p. x, P. y );
}
(4) Help button displayed on the form
This. formborderstyle = system. Windows. Forms. formborderstyle. fixedsingle;
This. helpbutton = true;
This. maximizebox = false;
This. minimizebox = false;
Click the Help button to display the Help File in chm format?

Handle the helpbuttonclicked event of the form:

System. Diagnostics. process. Start ("articlecollectorapi. chm ");

(5) differences between the anchor and dock attributes of controls
Anchor is used to set the distance between the control and the edge of the form!
The dock is used to set the control to stay close to an edge of the form or fill in the entire form.

(6) use the datagridview to display, update, and delete data

String connstr = @ "Server =. \ sqlexpress; initial catalog = myschool; uid = sa; Pwd = sa2008 ";
Dataset DS = new dataset ();
Sqldataadapter da;

// Display data

Private void loaddata ()
{
String strwhere;
If (combobox1.text = "male ")
Strwhere = "Sex = 'male '";
Else
If (combobox1.text = "")
Strwhere = "Sex = 'female '";
Else
Strwhere = "Sex = 'male' or sex = 'femal '";
String SQL = "select studentid, studentno, studentname, sex from student where" + strwhere;
DA = new sqldataadapter (SQL, connstr );

DS. Tables. Clear ();
Da. Fill (DS );
Datagridview1.datasource = Ds. Tables [0];

}
// Update data

Private void button2_click (Object sender, eventargs E)
{

// The SQL statement for updating the database is automatically generated, but the data must be from the same data table. Otherwise, update failed!
Sqlcommandbuilder CMDB = new sqlcommandbuilder (DA );

Da. Update (DS );
Loaddata ();
}

// Delete data

Private void Delete toolstripmenuitem_click (Object sender, eventargs E)
{
If (maid. Count = 0) // use fullrowselect for the selectionmode attribute
{
MessageBox. Show ("Please Select! ");
Return;
}
If (MessageBox. Show ("are you sure you want to delete it? "," Warning ", messageboxbuttons. yesno, messageboxicon. Warning) = dialogresult. Yes)
{
Using (sqlconnection conn = new sqlconnection (connstr ))
{
String SQL = "delete from student where studentid =" + (INT) datagridview1.selectedrows [0]. cells [0]. value;
Sqlcommand cmd = new sqlcommand (SQL, Conn );
Conn. open ();
Cmd. executenonquery ();
}
Loaddata ();
}
}

(7) Close the main form and a dialog box Indicating whether to exit is displayed:

Private void formmain_formclosing (Object sender, formclosingeventargs E)
{
If (MessageBox. Show ("are you sure you want to exit?", "system message", messageboxbuttons. okcancel, messageboxicon. Question) = dialogresult. Cancel)
{

E. Cancel = true;
}
}

Private void formmain_formclosed (Object sender, formclosedeventargs E)
{

Application. Exit ();
}

// Event code of the "exit" menu

Private void exit toolstripmenuitem_click (Object sender, eventargs E)
{
This. Close ();
}

(8) JavaScript access to the server control:

Server Control declaration:

<Asp: textbox id = "txtname" onblur = "checkname ()" runat = Server> </ASP: textbox> <span id = "error" style = "color: red "> </span> <br/>

Corresponding JavaScript code:
Function checkname ()
{
If(document.forms(0).txt name. value. length! = 6)
{
Document. getelementbyid ("<% = txterror. clientid %>"). value = "error ";
}
Else
Document. getelementbyid ('error'). innerhtml = "";
}

(9) after the form is sent back, keep the password in the password box.

Generally, after the form is sent back, the password box is automatically cleared. But sometimes we don't want. At this time, we can add the following code to avoid this problem.

Protectedvoidpage_load (objectsender, eventargse)

{

If (ispostback) // if it is a page resend

{

If (! (String. isnullorempty (txtpassword. Text. Trim ())))

{

Txtpassword. attributes ["value"] = txtpassword. text;

}

}

}

(10) rewrite the equals method to determine whether the object is equal

By default, the equals () method of the object class is used to determine whether two objects are equal. It is used to compare whether two objects reference the same object. To support equal values, you must override the equals virtual method.

Public override bool equals (Object OBJ)
{
// Convert the object to be compared to the current type
Student target = OBJ as student;

// If it is null and the type is different
If (target = NULL)
Return false;

If (target. Name = This. Name &&
Target. Gender = This. Gender &&
Target. Age = This. Age)
{
Return true;
}
Return false;
}

(11) filterindex attribute of filedialog

Note the description in msdn:

The index value of the first filter entry is 1. Not 0.

(12) restoredirectory attributes of filedialog

Description in msdn: If you have changed the directory when searching for a file, the value is true if the current directory is restored to the initial value in the dialog box. Otherwise, the value is false. The default value is false. After reading this description, is it still a confused O (∩ _ ∩) O?

In fact, this attribute actually controls the system in the current program. environment. currentdirectory, that is, when the attribute is set to true, system. environment. currentdirectory is always the folder directory from which the program starts. If it is set to false, the system. environment. currentdirectory is the last directory to open the file.

(13) after the page is refreshed, the scroll bar remains unchanged and remains in the original position.

ASP. NET 2.0 provides such a solution, you can set

<% @ Page maintainscrollpositiononpostback = "true" %>

Or set in Encoding

Page. maintainscrollpositiononpostback = true;

Or set it in Web. config.

<Pages maintainscrollpositiononpostback = "true"/>

.

(14) operate the bit field of the SQL Server database

The value of the bit field in the SQL Server database is 1 or 0. Therefore, the value of this field must be 1 or 0 when it is added or modified to the database.

However, when the bit field value is retrieved from the database, the corresponding value is true or false.

(15) Use guid

GUID (globally unified identifier) refers to the number generated on a machine, which ensures that all machines in the same time and space are unique. Generally, the platform provides APIs for generating guids. The generation algorithm is very interesting. It uses Ethernet Card addresses, nanoseconds, chip ID codes, and many possible numbers. The unique defect of GUID is that the generated result string is large.
1. a guid is a 128-bit integer (16 bytes). When using a unique identifier, you can use this integer between all computers and networks.

2. The GUID format is "XXXXXXXX-XXXX-xxxxxxxxxxxx", where each X is a hexadecimal number in the range of 0-9 or a-f. For example, 337c7f2b-7a34-4f50-9141-bab9e6478cc8 is a valid guid value.

3. No duplicate guid value is generated on any two computers in the world (koffer Note: it should be on the Earth. GUID is used to assign a unique identifier to a network or system with multiple nodes and computers.

Use guid in. net

GUID is widely used in. net, and. NET Framework provides a dedicated guid infrastructure.
Common guid structure methods include:
1) system. guid. newguid ()
Generate a new guid unique value
2) system. guid. newguid () tostring ()
Converts a guid value to a string for processing.

1. The result of guid. newguid (). tostring ("N") is:
38bddf48f43c48588e0d78761eaa1ce6
2. The result of guid. newguid (). tostring ("D") is:
57d99d89-caab-482a-a0e9-a0a803eed3ba
3. The result of guid. newguid (). tostring ("B") is:
{09f140d5-af72-44ba-a763-c861304b46f8}
4. The result of guid. newguid (). tostring ("p") is:
(778406c2-efff-4402-ab03-70a77d09c2b5)
The default value is 2nd.

Similarly, SQL Server well integrates the usage of guid. The SQL Server Data Type uniqueidentifier can store a guid value. You can use the newid () function to generate this value in SQL Server, or you can generate a guid outside SQL Server, and then manually insert this value.

(16) access the master page control on the Content Page

On the child page, you can use events to access the control properties of the master page.

Method 1:
(1) Description: The control type is converted to the corresponding control type through the master object lookup control.
Example: This. lblcontent. Text = (master. findcontrol ("lbltime") as label). text;
This. lblcontent. Text = (master. findcontrol ("lbltime") as label). text;
(2) The sub-page must contain some specified methods.
Protected void page_loadcomplete (Object sender, eventargs E)
{
This. lblcontent. Text = (master. findcontrol ("lbltime") as label). text;
}
"Page_loadcomplete" is an event triggered when the content page is loaded.
(3) You can also operate the master page function in the event.
Protected void button#click (Object sender, eventargs E)
{
(MASTER. findcontrol ("lbltime") as label). Text = "hello you ";
}

Method 2: Use strong references

<% @ Page Language = "C #" masterpagefile = "~ /Masterpage. Master "autoeventwireup =" true "codefile =" default2.aspx. cs "inherits =" default2 "Title =" untitled page "%>
<% @ Mastertype virtualpath = "~ /Masterpage. Master "%>

You can then define public attributes or methods on the master page.
Public String GetUserName ()
{
Return page. User. Identity. Name;
}
Call
Label1.text = "welcome" + master. GetUserName ();

(17) GO TO THE PREVIOUS PAGE

Method 1:
In the source code of aspx in Asp.net
<Input type = "button onclick =" javascript: window. History. Go (-1); "value =" back to previous page ">
Analysis: This is an HTML control. Through an onclick event, you can call a method in JavaScript. This is the simplest and also applies to static pages and ASP pages.
Method 2:
Use reponse. Write
Response. Write ("<script language = JavaScript> history. Go (-2); </SCRIPT>)
<A href = "#" onclick = "javascript: history. Back ();"> return to the previous page </a>
Because in Asp.net, when you press a button, the page is implemented. because of PostBack, the page is actually refreshed twice, and we want it for the first time, so it is ......
Method 3
Use response. Redirect () or server. Transfer ()
Add the following to page_load:
If (! Ispostback)
Viewstate ["retu"] = request. urlreferrer. tostring ();
Then add the following to the return button event:
Response. Redirect (viewstate ["retu"]. tostring ());
Or server. Transfer (viewstate ["retu"]. tostring ());
Request. urlreferrer can obtain the URL Information of the client's last request. We recommend that you make a judgment when using this information.
If (viewstate ["urlreferrer"]! = NULL)
Response. Redirect (viewstate ["urlreferrer"]. tostring ();
Else
Response. Write ("sorry, the current is the front page number");
Note the following when using request. urlreferrer:
1. If the document. location method is used on the previous page to navigate to the current page, request. urlreferrer returns a null value.
2. If there are two pages a and B, directly request page A in the browser and navigate to page B in the page_load event of page A, then request. urlreferrer returns NULL. Because the page has not been initialized in the page_load event, you cannot record the information of the current page. If you navigate to page B, you cannot obtain the information of the previous page.
3. clicking the refresh button will not change request. urlreferrer
Method 4:
In The onclick event of the button, enter
This. registerclientscriptblock ("e", "<script language = JavaScript> history. Go (-2); </SCRIPT> ");

 

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.