Asp. NET common 33 kinds of practical code

Source: Internet
Author: User
Tags foreach datetime empty eval exception handling header log tostring

1. Open a new window and transfer parameters:

Transfer parameters:

Response.Write ("")


Receive parameters:

String a = Request.QueryString ("id");
String B = Request.QueryString ("Id1");


2. Add a dialog box for the button

BUTTON1.ATTRIBUTES.ADD ("onclick", "return confirm (' Confirm? ')");
Button.attributes.add ("onclick", "If" (Confirm (' Are you sure ...? ')) {return true;} Else{return false;} ")


3. Delete table Selected records

int intempid = (int) Mydatagrid.datakeys[e.item.itemindex];
String deletecmd = "DELETE from Employee where emp_id =" + intempid.tostring ()


4. Delete the form record warning

private void datagrid_itemcreated (Object Sender,datagriditemeventargs e)
{
Switch (e.item.itemtype)
{
Case ListItemType.Item:
Case ListItemType.AlternatingItem:
Case ListItemType.EditItem:
TableCell Mytablecell;
Mytablecell = e.item.cells[14];
LinkButton Mydeletebutton;
Mydeletebutton = (LinkButton) mytablecell.controls[0];
MYDELETEBUTTON.ATTRIBUTES.ADD ("onclick", "return Confirm" (' You are sure you want to delete this message '); ");
Break
Default
Break
}

}


5. Click on a table row link another page

private void Grdcustomer_itemdatabound (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
Click on the form to open
if (E.item.itemtype = = ListItemType.Item | | e.item.itemtype = = listitemtype.alternatingitem)
E.item.attributes.add ("onclick", "window.open" (' default.aspx?id= "+ e.item.cells[0]. Text + "');
}


Double-click a table to connect to another page

In the ItemDataBind event

if (E.item.itemtype = = ListItemType.Item | | e.item.itemtype = = listitemtype.alternatingitem)
{
String Orderitemid =e.item.cells[1]. Text;
...
E.item.attributes.add ("OnDblClick", "location.href="). /shippedgrid.aspx?id= "+ Orderitemid +" "");
}


Double-click a table to open a new page

if (E.item.itemtype = = ListItemType.Item | | e.item.itemtype = = listitemtype.alternatingitem)
{
String Orderitemid =e.item.cells[1]. Text;
...
E.item.attributes.add ("OnDblClick", "open". /shippedgrid.aspx?id= "+ Orderitemid +" ")";
}


★ Special attention: "? id=" Can not be "? id ="

6. Table super Join column pass parameter

<%# DataBinder.Eval (Container.DataItem, data field 1)%> ' & Name= ' <%# DataBinder.Eval (Container.DataItem, "data field 2")%> '/ >


7. Click to change the color of the form

if (E.item.itemtype = = ListItemType.Item | | E.item.itemtype = = ListItemType.AlternatingItem)
{
E.item.attributes.add ("onclick", "this.style.backgroundcolor= ' #99cc00";
This.style.color= ' ButtonText '; this.style.cursor= ' default ';
}


Written in the _itemdatabound of the DataGrid.

if (E.item.itemtype = = ListItemType.Item | | E.item.itemtype = = ListItemType.AlternatingItem)
{
E.item.attributes.add ("onmouseover", "this.style.backgroundcolor= ' #99cc00";
This.style.color= ' ButtonText '; this.style.cursor= ' default ';
E.item.attributes.add ("onmouseout", "this.style.backgroundcolor="; this.style.color= '; ");
}



8. About date formats

Date format setting

Dataformatstring= "{0:YYYY-MM-DD}"


I think it should be in the Itembound incident.

e.items.cell["Your column"].text=datetime.parse (e.items.cell["Your column"].text. ToString ("Yyyy-mm-dd"))


9. Get the error message and go to the specified page

Instead of using Response.Redirect, you should use Server.Transfer

e.g

In Global.asax
protected void Application_Error (Object sender, EventArgs e) {
if (Server.GetLastError () is httpunhandledexception)
Server.Transfer ("myerrorpage.aspx");

The rest of the httpunhandledexception exception to ASP.net to deal with their own okay the:)
}


REDIRECT can cause Post-back to lose error messages, so page orientation should be done directly on the server side, so that you can get error messages on the error-handling page and handle them accordingly.

10. Empty Cookies

Cookie.expires=[datetime];
Response.Cookies ("UserName"). Expires = 0


11. Custom Exception Handling

Custom Exception Handling Classes
Using System;
Using System.Diagnostics;

Namespace Myappexception
{
<summary>
ApplicationException an inherited application exception handling class from the system exception class.
Automatically logs exception content to the Windows nt/2000 Application log
</summary>
public class AppException:System.ApplicationException
{
Public Appexception ()
{
if (applicationconfiguration.eventlogenabled) LogEvent ("An unknown error occurred.") ");
}

Public appexception (String message)
{
LogEvent (message);
}

Public appexception (String message,exception innerexception)
{
LogEvent (message);
if (innerexception!= null)
{
LogEvent (Innerexception.message);
}
}

Logging class
Using System;
Using System.Configuration;
Using System.Diagnostics;
Using System.IO;
Using System.Text;
Using System.Threading;

Namespace MyEventLog
{
<summary>
Event logging classes, providing event logging support
<remarks>
Defines 4 logging methods (Error, warning, info, trace)
</remarks>
</summary>
public class Applicationlog
{
<summary>
Log error messages to the Win2000/nt event log
<param name= "Message" The text information you need to record </param>
</summary>
public static void Writeerror (String message)
{
Writelog (tracelevel.error, message);
}

<summary>
Log warning messages to the Win2000/nt event log
<param name= "Message" The text information you need to record </param>
</summary>
public static void Writewarning (String message)
{
Writelog (tracelevel.warning, message);
}

<summary>
To log a hint to the Win2000/nt event log
<param name= "Message" The text information you need to record </param>
</summary>
public static void Writeinfo (String message)
{
Writelog (tracelevel.info, message);
}
<summary>
Log trace information to the Win2000/nt event log
<param name= "Message" The text information you need to record </param>
</summary>
public static void Writetrace (String message)
{
Writelog (tracelevel.verbose, message);
}

<summary>
Format text information that is logged to the event log
<param name= "Ex" the exception object that needs to be formatted </param>
<param name= "Catchinfo" > exception message header string. </param>
<retvalue>
The <para> the formatted exception information string, including the exception content and the trace stack. </para>
</retvalue>
</summary>
public static string FormatException (Exception ex, String Catchinfo)
{
StringBuilder Strbuilder = new StringBuilder ();
if (Catchinfo!= String.Empty)
{
Strbuilder.append (Catchinfo). Append ("\ r \ n");
}
Strbuilder.append (ex. Message). Append ("\ r \ n"). Append (ex. StackTrace);
return strbuilder.tostring ();
}

<summary>
Actual Event Log Write method
<param name= the level of information to be recorded (Error,warning,info,trace). </param>
<param name= "MessageText" > text to be recorded. </param>
</summary>
private static void Writelog (TraceLevel level, String MessageText)
{
Try
{
EventLogEntryType Logentrytype;
Switch (level)
{
Case TRACELEVEL.ERROR:
Logentrytype = EventLogEntryType.Error;
Break
Case tracelevel.warning:
Logentrytype = eventlogentrytype.warning;
Break
Case Tracelevel.info:
Logentrytype = eventlogentrytype.information;
Break
Case Tracelevel.verbose:
Logentrytype = Eventlogentrytype.successaudit;
Break
Default
Logentrytype = Eventlogentrytype.successaudit;
Break
}

EventLog EventLog = new EventLog ("Application", Applicationconfiguration.eventlogmachinename, Applicationconfiguration.eventlogsourcename);
Writing to the event log
EventLog.WriteEntry (MessageText, Logentrytype);

}
Catch {}//ignore any exceptions
}
}//class Applicationlog
}

12.Panel horizontal scrolling, vertical automatic expansion


13. Return to Tab





14.DataGrid Super Connection column

datanavigateurlfield= "field name" Datanavigateurlformatstring= "http://xx/inc/delete.aspx?id={0}"


15.DataGrid line changes color with mouse

private void Dgzf_itemdatabound (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (E.item.itemtype!=listitemtype.header)
{
E.item.attributes.add ("onmouseout", "this.style.backgroundcolor=\" "+e.item.style[" Background-color "]+" "");
E.item.attributes.add ("onmouseover", "this.style.backgroundcolor=\" "+" #EFF3F7 "+" ");
}
}


16. Template columns




Background code

protected void Checkall_checkedchanged (object sender, System.EventArgs e)
{
Change the selection of columns to achieve either a full or a full selection.
CheckBox Chkexport;
if (checkall.checked)
{
foreach (DataGridItem odatagriditem in Mydatagrid.items)
{
Chkexport = (checkbox) Odatagriditem.findcontrol ("Chkexport");
Chkexport.checked = true;
}
}
Else
{
foreach (DataGridItem odatagriditem in Mydatagrid.items)
{
Chkexport = (checkbox) Odatagriditem.findcontrol ("Chkexport");
chkexport.checked = false;
}
}
}


17. Number format

"<% #Container. DataItem (" price ")%> result is 500.0000, how to format into 500.00?"

<% #Container. DataItem ("Price", "{0:¥#,# #0.00}")%>

int i=123456;
String s=i.tostring ("###,###.00");



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.