Tips C #

Source: Internet
Author: User

1. Keep the scroll bar position after callback:

In asp.net1.1, it is very painful to keep the scroll bar position after callback, especially if there is a grid in the page and you want to edit a particular row. In order not to stay on the desired line, the page reloads and must scroll down at the top. In ASP2.0, simply add the Maintainscrollpostiononpostback attribute to the page's properties to
<%@ page language= "C #" maintainscrollpositiononpostback= "true" autoeventwireup= "true" codefile= "" inherits= ""% >

2. Anonymous delegate implementation of custom sorting

public void Sortbycommentcount (list<article>articlelist, bool Ascending)
{
Articlelist.sort (Delegate (Articlea, article B)
{
Return (a.commentcount-b.commentcount) * (Ascending 1:-1);
});
}

3. ReadOnly is a run-time constant, const is a compile-time constant, the former is flexible, the latter is efficient; the former can be used for any type, the latter only for numbers and strings

4. Obtain the client computer name
System.Net.Dns.GetHostEntry (Request.userhostname). HostName;

5. Common collections:
CollectionsUtil creates a collection that ignores string casing.
HybridDictionary use ListDictionary to implement IDictionary when the collection is small, and then switch to Hashtable when the collection becomes larger.
ListDictionary uses a single-link list to implement IDictionary. Recommended for collections that typically contain 10 or 10 of the following items.
NameObjectCollectionBase provides an abstract base class for the associated String Key and a collection of Object values that can be accessed by key or index.
Nameobjectcollectionbase.keyscollection represents a collection of String keys for the collection.
NameValueCollection represents a collection of associative string keys and string values that can be accessed through a key or index.
OrderedDictionary represents a collection of key/value pairs sorted by key/index.
StringCollection represents a collection of strings.
StringDictionary implements a hash table by strongly typing the key and value into a string rather than an object.

6. ListDictionary, Hashtable, HybridDictionary

Small Data Volume: ListDictionary is better than hashtable,10 or 10 or less
Big Data Volume: Hashtable is better than listdictionary,10
Uncertain data volume: hybriddictionary, the ability to determine whether your data should be stored listdictionary or hashtable
The above three, all belong to Hashtable, that dictionary and they have what difference?
Dictionary<>: recommended in single-threaded applications, with a generic advantage, with faster reads, better capacity utilization, and the capability to arrange data in the order of insertion (note: But the order is disrupted when the call to remove () deletes the feast point), so it is used in situations that need to manifest the order Dictionary can get a certain convenience
Hashtable: The default Hashtable allows single-threaded writes, multithreaded reads, and Hashtable further calls to the Synchronized () method to obtain a fully thread-safe type. While Dictionary is not thread-safe, it must be protected by the use of the lock statement, and the efficiency is greatly reduced

7. The volatile modifier is typically used for access by multiple threads without using the lock statement

8. The implicit keyword is used to declare an implicit user-defined type conversion operator, such as A+b

9. The as operator is similar to a cast operation, but if the conversion is not a row, as returns null instead of throwing an exception. Note that the AS operator only performs reference conversions and boxing conversions. The as operator cannot perform other transformations, such as user-defined conversions, which should be performed using cast expressions.

10. The value of the control between the item is just a property of HttpContext. Httpcontext.item
In other words, this property is for a single request, and each time a user makes a HttpContext instance of the request, there is no user sharing problem.
In general, item is only used for control development when storing some common values, and the value in item will be re-established when the next request arrives.

11. The following objects are passed by reference:
Hashtable[including taking out of the session and not having to cram it back in.
SqlDataReader
StringBuilder
Dictionary<t, t>

NameValueCollection usage
NameValueCollection MyCol = new NameValueCollection ();
Mycol.add ("Red", "Rojo");
Mycol.add ("Green", "Verde");
Mycol.add ("Blue", "Azul");
Mycol.add ("Red", "rouge");
Mycol.add ("Red", "BBB");
Print:red ROJO,ROUGE,BBB
Green Verde
Blue Azul

HttpCookie precautions
Cookies. Values.add if key is present, it is incremented above the key as 010 before add, and if you continue to the key value add becomes 010,010
Cookies. Values[key] This key does not exist or can be added, recommended

File.exists (FileName); Whether the file exists
Directory.Exists (FolderName); Whether the directory (folder) exists

15. Set default values after binding DropDownList bindings
DdlBranch.Items.FindByText ("head Office"). Selected =true;

16. Bind to Simple properties: <% #UserName%>
Bind to Collection: <asp:listbox id= "ListBox1" datasource= ' <%# myarray%> ' runat= "Server" >
Binding to an expression: <%# (class1.property1.ToString () + "," + class1.property2.ToString ())%>
Bind to method return value: <%# getsafestring (str)%>
Bind to hashtable:<%# ((DictionaryEntry) Container.DataItem). Key%>
Bind to arraylist:<% #Container. DataItem%>

. ASP. NET Server controls

Name is obtained with this.UniqueID.ToString ()
ID is obtained with this.ClientID.ToString ()

How to execute a parent control by ASP.
Page P = this. Parent.page;
Type PageType = P.gettype ();
MethodInfo mi = pagetype.getmethod ("Loading");
String sqlwhere = Getwhere (HSR);
Mi. Invoke (P, new object[] {sqlwhere});

19. Server-side FileUpload upload controls how to disable manual entry

<asp:fileupload id= "FileUpload1" runat= "Server" height= "22px" width= "412px" onkeydown= "Event.returnvalue=false;" Onpaste= "return false"/>

20. Data connection Shutdown issues

1.DataReader off: If not dr.isclosed then dr.closed (), if the DR is not closed, the CN is closed directly, then the DR automatically shuts down.
2.DataSet There is no problem with closing or not
3.DataTable There is a problem with the shutdown, and the. NET default is set to, when using Dt.fill (DS), it automatically opens, and automatically shuts down after filling

21. Clever Intercept date datestring.split (') [0]

22. Do not use + to connect two path strings
With Path.Combine ("String 1", "String 2")
Like what
Path.Combine (@ "C:\AAA\BBB", "CCC")//C:\AAA\BBB\CCC--automatically complements a slash
Path.Combine (@ "C:\AAA\BBB\", @ "\CCC")//same result, automatic removal of a diagonal bar
Path.Combine (@ "C:\AAA\BBB", @ "... \CCC ")//C:\AAA\CCC

    1. Multiple parameters in an Access database

String sql = "Update Tb_typeset[email protected],[email protected]where[email protected]";
Oledbparameter[]parameters = {

New OleDbParameter ("@typename", oledbtype.varchar,50),
New OleDbParameter ("@describe2", oledbtype.varchar,50),
New OleDbParameter ("@id", oledbtype.integer,4)};


Parameters[0]. Value = Model.typename;
PARAMETERS[1]. Value = Model.describe2;
PARAMETERS[2]. Value = model.id;

In Access it is actually required that the order correspond.

-----------------------------------------

Tips C #

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.