Summary of common issues in ASP. Net development

Source: Internet
Author: User

1. open a new window and send parameters:

Transfer Parameters:

Response. write ("<script> window. open
('*. Aspx? Id = "+ this. DropDownList1.SelectIndex +" & id1 = "+... +" ') </script> ")

Receiving parameters:

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

2. Add dialog box for button

Button1.Attributes. Add ("onclick", "return confirm ('OK? ')");
Button. attributes. add ("onclick", "if (confirm ('Are you sure ...? '))
{Return true;} else {return false ;}")

3. Delete selected table records

Int intEmpID = (int) MyDataGrid. DataKeys [e. Item. ItemIndex];
String deleteCmd = "DELETE from Employee where emp_id =" + intEmpID. ToString ()

4. Delete table 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 ('Are you sure you want to delete this information ');");
Break;
Default:
Break;
}
}

5. Click the table row link to another page.

Private void grdCustomer_ItemDataBound
(Object sender, System. Web. UI. WebControls. DataGridItemEventArgs e)
{
// Click Open Table
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 = 'HTTP: // developer.51cto.com/art/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 + "')");
}

★Note :【? Id =] cannot be 【? Id =]

6. Table hyperjoin column Transfer Parameters

<Asp: HyperLinkColumn Target = "_ blank" headertext = "id" DataTextField = "id"
NavigateUrl = "aaa. aspx? Id = '<% # DataBinder. Eval (Container. DataItem, "data field 1") %>'
& Name = '<% # DataBinder. Eval (Container. DataItem, "data field 2") %>'/>

7. Click to change the color of the table.

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 _ 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 Format

Date Format setting

DataFormatString = "{0: yyyy-MM-dd }"

I think it should be in the itembound event

E. items. cell ["your column"]. text = DateTime. parse (e. items. cell ["your column"]. text. toString ("yyyy-MM-dd "))

9. Get error information 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 remaining non-HttpUnhandledException exceptions are handled by ASP. NET itself and okay will be handled :)
}

Redirect will lead to post-back loss of error information, so the page orientation should be executed directly on the server side, so that the error information can be obtained on the error handling page and processed accordingly

10. Clear cookies

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

11. Custom Exception Handling

// Custom exception handling class
Using System;
Using System. Diagnostics;
Namespace MyAppException
{
/// <Summary>
/// Application exception handling class inherited from the system exception class ApplicationException.
/// Automatically record the exception content to the application logs of Windows NT/2000
/// </Summary>
Public class AppException: System. ApplicationException
{
Public AppException ()
{
If (ApplicationConfiguration. EventLogEnabled)
LogEvent ("an unknown error occurs. ");
}
Public AppException (string message)
{
LogEvent (message );
}
Public AppException (string message, Exception innerException)
{
LogEvent (message );
If (innerException! = Null)
{
LogEvent (innerException. Message );
}
}
// Log record type
Using System;
Using System. Configuration;
Using System. Diagnostics;
Using System. IO;
Using System. Text;
Using System. Threading;
Namespace MyEventLog
{
/// <Summary>
/// Event logging class, supporting event logging
/// <Remarks>
/// Defines four logging methods (error, warning, info, trace)
/// </Remarks>
/// </Summary>
Public class ApplicationLog
{
/// <Summary>
/// Record the error information to the Win2000/NT Event Log
/// <Param name = "message"> text information to be recorded </param>
/// </Summary>
Public static void WriteError (String message)
{

WriteLog (TraceLevel. Error, message );
}

/// <Summary>
/// Record the warning information to the Win2000/NT Event Log
/// <Param name = "message"> text information to be recorded </param>
/// </Summary>
Public static void WriteWarning (String message)
{

WriteLog (TraceLevel. Warning, message );
}

/// <Summary>
/// Record the prompt information to the Win2000/NT Event Log
/// <Param name = "message"> text information to be recorded </param>
/// </Summary>
Public static void WriteInfo (String message)
{
WriteLog (TraceLevel. Info, message );
}
/// <Summary>
/// Record tracking information to Win2000/NT Event Logs
/// <Param name = "message"> text information to be recorded </param>
/// </Summary>
Public static void WriteTrace (String message)
{

WriteLog (TraceLevel. Verbose, message );
}

/// <Summary>
/// Format the text information recorded in the event log
/// <Param name = "ex"> the exception object to be formatted </param>
/// <Param name = "catchInfo"> exception message title string. </param>
/// <Retvalue>
/// <Para> formatted exception information string, including the exception content and 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 Writing Method
/// <Param name = "level"> information level (error, warning, info, trace) to be recorded. </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 );
// Write Event Logs
EventLog. WriteEntry (messageText, LogEntryType );

}
Catch {} // ignore any exceptions
}
} // Class ApplicationLog
}


12. horizontal Panel scrolling and vertical auto Scaling

<Asp: panel style = "overflow-x: scroll; overflow-y: auto;"> </asp: panel>

13. Press enter to convert to Tab

<Script language = "javascript" for = "document" event = "onkeydown">
If (event. keyCode = 13 & event. srcElement. type! = 'Button '&&
Event. srcElement. type! = 'Submit '& event. srcElement. type! = 'Reset'
& Event. srcElement. type! = ''& Event. srcElement. type! = 'Textea ');
Event. keyCode = 9;
</Script>
Onkeydown = "if (event. keyCode = 13) event. keyCode = 9"
Http://dotnet.aspx.cc/exam/enter2tab.aspx

14. DataGrid super join Column

DataNavigateUrlField = "field name" DataNavigateUrlFormatString = "http: // xx/inc/delete. aspx? ID = {0 }"


15. The row of the DataGrid changes color with the 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 Column

<ASP: TEMPLATECOLUMN visible = "False" sortexpression = "demo" headertext = "ID">
<ITEMTEMPLATE>
<ASP: LABEL text = '<% # DataBinder. Eval (Container. DataItem,
"ArticleID") %> 'runat = "server" width = "80%" id = "lblColumn"/>
</ITEMTEMPLATE>
</ASP: TEMPLATECOLUMN>
<ASP: TEMPLATECOLUMN headertext = "selected">
<HEADERSTYLE wrap = "False" horizontalalign = "Center"> </HEADERSTYLE>
<ITEMTEMPLATE>
<ASP: CHECKBOX id = "chkExport" runat = "server"/>
</ITEMTEMPLATE>
<EDITITEMTEMPLATE>
<ASP: CHECKBOX id = "chkExportON" runat = "server" enabled = "true"/>
</EDITITEMTEMPLATE>
</ASP: TEMPLATECOLUMN>

Background code

Protected void CheckAll_CheckedChanged (object sender, System. EventArgs e)
{
// Change the column selection to select all or all columns.
CheckBox chkExport;
If (CheckAll. Checked)
{
Foreach (maid in MyDataGrid. Items)
{
ChkExport = (CheckBox) oDataGridItem. FindControl ("chkExport ");
ChkExport. Checked = true;
}
}
Else
{
Foreach (maid in MyDataGrid. Items)
{
ChkExport = (CheckBox) oDataGridItem. FindControl ("chkExport ");
ChkExport. Checked = false;
}
}
}

17. digit formatting

The result of <% # Container. DataItem ("price") %> is 500.0000. How to format it to 500.00 ?]
<% # Container. DataItem ("price", "{0: ¥ #,## 0.00}") %>
Int I = 123456;
String s = I. ToString ("###,##. 00 ");

18. Date formatting

[Aspx page: <% # DataBinder. Eval (Container. DataItem, "Company_Ureg_Date") %>
Shown as: 19:44:28
I only want]

<% # DataBinder. Eval (Container. DataItem, "Company_Ureg_Date", "{0: yyyy-M-d}") %>

How should I change it?


[Format date]
It is usually an object.
(DateTime) objectFromDB). ToString ("yyyy-MM-dd ");

[Date verification expression]
A. The correct input format is as follows: [], [10:29:39], []

^ (\ D {2} ([02468] [048]) | ([13579] [26]) [\-\/\ s]? (0? [13578]) | (1 [02])
[\-\/\ S]? (0? [1-9]) | ([1-2] [0-9]) | (3 [01]) | (0? [469]) | (11) [\-\/\ s]? (0? [1-9]) |
([1-2] [0-9]) | (30) | (0? 2 [\-\/\ s]? (0? [1-9]) | ([1-2] [0-9]) | (\ d {2} ([02468]
[1235679]) | ([13579] [01345789]) [\-\/\ s]? (0? [13578]) | (1 [02]) [\-\/\ s]
? (0? [1-9]) | ([1-2] [0-9]) | (3 [01]) | (0? [469]) | (11) [\-\/\ s]? (0? [1-9]) |
([1-2] [0-9]) | (30) | (0? 2 [\-\/\ s]? (0? [1-9]) | (1 [0-9]) | (2 [0-8])
(\ S (0? [1-9]) | (1 [0-2]) \ :( [0-5] [0-9]) (\ s) | (\ :( [0-5] [0-9]) \ s ))
([AM | PM | am | pm] {2, 2 })))? $

B. The following correct input format: [0001-12-31], [9999 09 30], [2002/03/03]

^ \ D {4} [\-\/\ s]? (0 [13578]) | (1 [02]) [\-\/\ s]? ([0-2] [0-9]) | (3 [01]) |
(0 [469]) | (11) [\-\/\ s]? ([0-2] [0-9]) | (30) | (02 [\-\/\ s]? [0-2] [0-9]) $

[Case-sensitive conversion]

HttpUtility. HtmlEncode (string );
HttpUtility. HtmlDecode (string)
19. How to set global variables

In Global. asax
Application_Start () event
Add Application [attribute name] = xxx;
Is your global variable

20. How do I connect to the connection generated by HyperLinkColumn and click Connect to open a new window?

HyperLinkColumn has a property Target, which can be set to "_ blank" (Target = "_ blank ")

[ASPNETMENU] Click the menu item to bring up a new window
Add URLTarget = "_ blank" to the menu item of your menuData. xml file"
For example:

<? Xml version = "1.0" encoding = "GB2312"?>
<MenuData ImagesBaseURL = "images/">
<MenuGroup>
<MenuItem Label = "internal reference information" URL = "Infomation. aspx">
<MenuGroup ID = "BBC">
<MenuItem Label = "announcement information" URL = "Infomation. aspx"
URLTarget = "_ blank" LeftIcon = "file.gif"/>
<MenuItem Label = "" URL = "NewInfo. aspx" LeftIcon = "file.gif"/>
......

Upgrade your aspnetmenu to version 1.2.

21. Read the TextBox value of the DataGrid Control

Foreach (DataGrid dgi in yourDataGrid. Items)
{
TextBox tb = (TextBox) dgi. FindControl ("yourTextBoxId ");
Tb. Text ....
}

22. three template columns in the DataGrid contain Textbox columns DG_ShuLiang (Quantity) DG_DanJian (unit price) DG_JinE (amount) in 5.6.7, respectively, it is required that the amount be calculated automatically when the quantity and unit price are entered: quantity * unit price = amount, and the input time limit must be numeric. how can I use a client script to implement this function?

[Si GUI 〗

<Asp: TemplateColumn HeaderText = "quantity">
<ItemTemplate>
<Asp: TextBox id = "ShuLiang" runat = 'server'
Text = '<% # DataBinder. Eval (Container. DataItem, "DG_ShuLiang") %>'
Onkeyup = "javascript: DoCal ()"
/>

<Asp: RegularExpressionValidator id = "revS" runat = "server"
ControlToValidate = "ShuLiang" ErrorMessage = "must be integer" ValidationExpression = "^ \ d + $"/>
</ItemTemplate>
</Asp: TemplateColumn>

<Asp: TemplateColumn HeaderText = "unit price">
<ItemTemplate>
<Asp: TextBox id = "DanJian" runat = 'server'
Text = '<% # DataBinder. Eval (Container. DataItem, "DG_DanJian") %>'
Onkeyup = "javascript: DoCal ()"
/>

<Asp: RegularExpressionValidator id = "revS2" runat = "server"
ControlToValidate = "DanJian" ErrorMessage = "must be numeric" ValidationExpression = "^ \ d + (\. \ d *)? $ "/>

</ItemTemplate>
</Asp: TemplateColumn>

<Asp: TemplateColumn HeaderText = "amount">
<ItemTemplate>
<Asp: TextBox id = "JinE" runat = 'server'
Text = '<% # DataBinder. Eval (Container. DataItem, "DG_JinE") %>'/>
</ItemTemplate>
</Asp: TemplateColumn>
<Script language = "javascript">
Function DoCal ()
{
Var e = event. srcElement;
Var row = e. parentNode. parentNode;
Var txts = row. all. tags ("INPUT ");
If (! Txts. length | txts. length <3)
Return;

Var q = txts [txts. length-3]. value;
Var p = txts [txts. length-2]. value;
If (isNaN (q) | isNaN (p ))
Return;
Q = parseInt (q );
P = parseFloat (p );
Txts [txts. length-1]. value = (q * p). toFixed (2 );
}
</Script>

23. Why is the row under the current row selected by the datagrid always refreshed and then rolled to the top? The row selected just now cannot be seen due to the relationship between the screen.

Page_load
Page. smartNavigation = true

24. modify data in the Datagrid. When you click the edit key, the data appears in the text box. How do I control the size of the text box?

Private void maid (obj sender, maid e)
{
For (int I = 0; I <e. Item. Cells. Count-1; I ++)
If (e. Item. ItemType = ListItemType. EditType)
{
E. Item. Cells [I]. Attributes. Add ("Width", "80px ")
}
}

25. Dialog Box

Private static string ScriptBegin = "<script language = \" JavaScript \ "> ";
Private static string ScriptEnd = "</script> ";
Public static void ConfirmMessageBox (string PageTarget, string Content)
{
String ConfirmContent = "var retValue = window. confirm ('"+ Content +"'); "+" if (retValue) {window. location = '"+ PageTarget + "';}";

ConfirmContent = ScriptBegin + ConfirmContent + ScriptEnd;

Page ParameterPage = (Page) System. Web. HttpContext. Current. Handler;
ParameterPage. RegisterStartupScript ("confirm", ConfirmContent );
// Response. Write (strScript );

}

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.