Asp. NET Common Code _asp.net

Source: Internet
Author: User
Tags bind current time datetime eval exception handling

1. Open a new window and transfer parameters:
Transfer parameters:
Response.Write ("<script>window.open" (' *.aspx?id= ') +this. dropdownlist1.selectindex+ "&id1=" +...+ "') </script>")

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


2. Add a dialog box for the button


Transfer parameters:
Response.Write ("<script>window.open" (' *.aspx?id= ') +this. dropdownlist1.selectindex+ "&id1=" +...+ "') </script>")

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
<asp:hyperlinkcolumn target= "_blank" headertext= "ID number" 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 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


{


&lt;summary&gt;


Event logging classes, providing event logging support


&lt;remarks&gt;


Defines 4 logging methods (Error, warning, info, trace)


&lt;/remarks&gt;


&lt;/summary&gt;


public class Applicationlog


{


&lt;summary&gt;


Log error messages to the Win2000/nt event log


&lt;param name= "message" &gt; Text information to be recorded &lt;/param&gt;


&lt;/summary&gt;


public static void Writeerror (String message)


{





Writelog (tracelevel.error, message);


}





&lt;summary&gt;


Log warning messages to the Win2000/nt event log


&lt;param name= "message" &gt; Text information to be recorded &lt;/param&gt;


&lt;/summary&gt;


public static void Writewarning (String message)


{





Writelog (tracelevel.warning, message);


}





&lt;summary&gt;


To log a hint to the Win2000/nt event log


&lt;param name= "message" &gt; Text information to be recorded &lt;/param&gt;


&lt;/summary&gt;


public static void Writeinfo (String message)


{


Writelog (tracelevel.info, message);


}


&lt;summary&gt;


Log trace information to the Win2000/nt event log


&lt;param name= "message" &gt; Text information to be recorded &lt;/param&gt;


&lt;/summary&gt;


public static void Writetrace (String message)


{





Writelog (tracelevel.verbose, message);


}





&lt;summary&gt;


Format text information that is logged to the event log


&lt;param name= "Ex" &gt; Exception object to be formatted &lt;/param&gt;


&lt;param name= "Catchinfo" &gt; Exception information title string .&lt;/param&gt;


&lt;retvalue&gt;


&lt;para&gt; format exception information string, including exception content and trace stack .&lt;/para&gt;


&lt;/retvalue&gt;


&lt;/summary&gt;


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 ();


}

&lt;summary&gt;


Actual Event Log Write method


&lt;param Name= level &gt; Levels to record information (Error,warning,info,trace) .&lt;/param&gt;


&lt;param name= "MessageText" &gt; Text to be recorded .&lt;/param&gt;


&lt;/summary&gt;


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.inf


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
<asp:panel style= "Overflow-x:scroll;overflow-y:auto;" ></asp:panel>


13. Return 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!= ' TextArea ');
event.keycode=9;
</script>

OnKeydown= "if (event.keycode==13) event.keycode=9"

Http://dotnet.aspx.cc/exam/enter2tab.aspx


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
<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= "Checked" >
<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 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.}")%>

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

18. Date format

aspx page: <%# databinder.eval (Container.DataItem, "company_ureg_date")%>
Displayed as: 2004-8-11 19:44:28
I only want: 2004-8-11 "

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

How should it be changed?


"Format Date"
Take it out, it's usually object.
((DateTime) objectfromdb). ToString ("Yyyy-mm-dd");


"Validation Expression for date"
A. The following correct input format: [2004-2-29], [2004-02-29 10:29:39 PM], [2004/12/31]

^ ((\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 Conversion"

Httputility.htmlencode (string);
Httputility.htmldecode (String)

19. How to set global variables
In Global.asax

In the Application_Start () event

Add application[property name] = XXX;

Is your global variable.

20. How to make a connection to the hyperlinkcolumn generated, click on the connection, open a new window?

HyperLinkColumn has a property target that sets the value of the device to "_blank". (target= "_blank")

"Aspnetmenu" click menu item to pop up a new window
Add urltarget= "_blank" to the menu item in your Menudata.xml file
Such as:
<?xml version= "1.0" encoding= "GB2312"?>
<menudata imagesbaseurl= "images/" >
<MenuGroup>
<menuitem label= "Internal reference information" url= "infomation.aspx" >
<menugroup id= "BBC" >
<menuitem label= "Bulletin Information" url= "infomation.aspx" urltarget= "_blank" lefticon= "file.gif"/>
<menuitem label= "Preparation of Information bulletin" url= "newinfo.aspx" lefticon= "File.gif"/>
......
It's best to upgrade your Aspnetmenu to version 1.2.

21. Commissioned Discussion
http://community.csdn.net/Expert/topic/2651/2651579.xml?temp=.7183191
Http://dev.csdn.net/develop/article/22/22951.shtm

22. Reading DataGrid control TextBox value

foreach (DataGrid dgi in Yourdatagrid.items)
{
TextBox TB = (textbox) Dgi. FindControl ("Yourtextboxid");
Tb. Text .....
}

23. In the DataGrid, 3 template columns contain a textbox of Dg_shuliang (quantity) Dg_danjian (unit price) Dg_jine (amount) respectively in 5.6.7, requiring that the amount be automatically calculated at the time of input quantity and unit price that is: quantity * unit Price = The amount also requires the input time limit to the numeric type. How do I implement this feature with client script?

Shi
<asp:templatecolumn headertext= "Quantity" >
<ItemTemplate>
<asp:textbox id= "Shuliang" runat= ' text= ' <%# databinder.eval (Container.DataItem, "DG_ShuLiang")%> '
onkeyup= "javascript:docal ()"
/>

<asp:regularexpressionvalidator id= "revs" runat= "controltovalidate=" Shuliang "errormessage=" must be Integer "validationexpression=" ^\d+$ "/>
</ItemTemplate>
</asp:TemplateColumn>

<asp:templatecolumn headertext= "Unit Price" >
<ItemTemplate>
<asp:textbox id= "Danjian" runat= ' text= ' <%# databinder.eval (Container.DataItem, "DG_DanJian")%> '
onkeyup= "javascript:docal ()"
/>

<asp:regularexpressionvalidator id= "revS2" runat= "controltovalidate=" Danjian "errormessage=" must be Numeric "validationexpression=" ^\d+ (\.\d*) $ "/>

</ItemTemplate>
</asp:TemplateColumn>

<asp:templatecolumn headertext= "Amount" >
<ItemTemplate>
<asp:textbox id= "Jine" runat= ' 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>


24.datagrid Select to compare the rows below, why always refresh, and then scroll to the top, just select the line because the screen relationship will not see the
Page_Load
Page.smartnavigation=true

25. Modify the data in the DataGrid, when you click on the edit key, the data appears in the text box, how to control the size of the text box?

private void Datagrid1_itemdatabound (obj Sender,datagriditemeventargs 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")

}
}


26. 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);

}

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

27. Format time: String aa=datetime.now.tostring ("yyyy mm month DD day");

1.1 to take the current month and the day seconds
Currenttime=system.datetime.now;

1.2 Take as the year before last
int year = DateTime.Now.Year;

1.3 Take the current month
int month = DateTime.Now.Month;

1.4 Take the current day
int day = DateTime.Now.Day;

1.5 Take current time
int = DateTime.Now.Hour;

1.6 Take the current score
int points = DateTime.Now.Minute;

1.7 Take the current second
int seconds = DateTime.Now.Second;

1.8 Take the current millisecond
int milliseconds = DateTime.Now.Millisecond;

28. Customize the paging code:

Define variables First: public static int pagecount; Total page Count

public static int curpageindex=1; Current page

Next page:

if (Datagrid1.currentpageindex < (datagrid1.pagecount-1))

{

Datagrid1.currentpageindex + 1;

Curpageindex+=1;

}

Bind (); DATAGRID1 Data-binding function

Previous page:

if (Datagrid1.currentpageindex >0)

{

Datagrid1.currentpageindex + 1;

Curpageindex-=1;

}

Bind (); DATAGRID1 Data-binding function

Direct page Jump:

int A=int. Parse (JumpPage.Value.Trim ());//jumppage.value.trim () is a jump value

if (A<datagrid1.pagecount)

{

This. Datagrid1.currentpageindex=a;

}

Bind ();

29. DataGrid use:

3. 1 Add Delete confirmation:

private void Datagrid1_itemcreated (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)

{

foreach (DataGridItem di in this.) Datagrid1.items)

{

if (di. itemtype==listitemtype.item| | Di. Itemtype==listitemtype.alternatingitem)

{

((LinkButton) di. CELLS[8]. Controls[0]). Attributes.Add ("onclick", "return confirm (' Confirm deletion of this item? ');");

}

}

}

3. 2 Styles Alternating:

ListItemType itemType = E.item.itemtype;

if (ItemType = = ListItemType.Item)

{

e.item.attributes["Onmouseout"] = "javascript:this.style.backgroundcolor= ' #FFFFFF ';";

e.item.attributes["onmouseover"] = "javascript:this.style.backgroundcolor= ' #d9ece1 '; cursor= ' hand ';";

}

else if (ItemType = = ListItemType.AlternatingItem)

{

e.item.attributes["Onmouseout"] = "javascript:this.style.backgroundcolor= ' #a0d7c4 ';";

e.item.attributes["onmouseover"] = "javascript:this.style.backgroundcolor= ' #d9ece1 '; cursor= ' hand ';";

}

3. 3 Add a numbered column:

DataTable dt= c.executertntableforaccess (sqltxt); Execute the DataTable returned by SQL

DataColumn Dc=dt. Columns.Add ("Number", System.Type.GetType ("System.String"));

for (int i=0;i<dt. rows.count;i++)

{

Dt. rows[i]["Number"]= (i+1). ToString ();

}

DATAGRID1.DATASOURCE=DT;

Datagrid1.databind ();

3. 4 DataGrid1 Add a checkbox, add a full selection box to the page

private void Checkbox2_checkedchanged (object sender, System.EventArgs e)

{

foreach (DataGridItem thisitem in Datagrid1.items)

{

(CheckBox) Thisitem. Cells[0]. CONTROLS[1]). checked=checkbox2.checked;

}

}

Delete all the data displayed in the current page DataGrid1

foreach (DataGridItem thisitem in Datagrid1.items)

{

if ((CheckBox) Thisitem. Cells[0]. CONTROLS[1]). Checked)

{

String strloginid= Datagrid1.datakeys[thisitem. ItemIndex]. ToString ();

Del (Strloginid); Delete function

}

}

30. When a file is in a different directory, you need to get the database connection string (if the connection string is Web.config and then initialized in global.asax)

Add the following code to the Application_Start:

application["ConnStr"]=this. context.request.physicalapplicationpath+configurationsettings.appsettings["ConnStr"]. ToString ();

31. Variable. ToString ()
Character conversion to string
12345.ToString ("n"); Generate 12,345.00
12345.ToString ("C"); Generate ¥12,345.00
12345.ToString ("E"); Generate 1.234500e+004
12345.ToString ("F4"); Generate 12345.0000
12345.ToString ("X"); Generate 3039 (16 binary)
12345.ToString ("P"); Generate 1,234,500.00%

32, variable. Substring (parameter 1, parameter 2);
Intercepts a portion of the string, parameter 1 is the left starting bit, and the parameter 2 is the Intercept number.
such as: string S1 = str. Substring (0,2);


34. Log on to other websites on your own website: (If your page is nested, because a page can only have a form, then you can guide another page to submit login information)


http://220.194.55.68:6080/login.php?retid=7259 " method= "POST"


The name of the text box must be the name on the page you want to log on, if the source code is not available, you can use Vsniffer to see.
Here is the code to get the login information entered by the User:


String name;
name=request.querystring["EmailName"];

Try
{
int A=name. IndexOf ("@", 0,name.) Length);
F_user. Value=name. Substring (0,a);
F_domain. Value=name. Substring (A+1,name. length-(a+1));
F_pass. value=request.querystring["PSW"];
}

Catch
{
Script.alert ("Wrong mailbox!");
Server.Transfer ("index.aspx");
}

35. Warning window

/**////<summary>
Server-side Pop-up Alert dialog box
</summary>
<param name= "str_message" > Hint message, Example: "Cannot be empty!" </param>
<param name= "page" >page class </param>
public void Alert (String str_message,page Page)
{
Page. RegisterStartupScript ("", "<script>alert" (' +str_message+ ");</script>");
}

36. Overload this warning window to get the focus of a control


/**////<summary>
Server-side Pop-up Alert dialog box, and the control gets focus
</summary>
<param name= "Str_ctl_name" > Get focus Control ID values, such as:txt_name</param>
<param name= "Str_message" > Message, Example: "Please enter your name!" </param>
<param name= "page" >page class </param>
public void Alert (string str_ctl_name,string str_message,page Page)
{
Page. RegisterStartupScript ("", "<script>alert (' +str_message+");d ocument.forms (0). " +str_ctl_name+ ". focus (); Document.forms (0). " +str_ctl_name+ ". Select ();</script>");
}

37. Confirmation dialog box


/**////<summary>
Server-side pop-up confirm dialog box
</summary>
<param name= "str_message" > Hint message, Example: "Do you confirm delete!" </param>
<param name= "btn" > Hide Botton button ID values, such as:btn_flow</param>
<param name= "page" >page class </param>
public void Confirm (string str_message,string btn,page Page)
{
Page. RegisterStartupScript ("", "<script> If" (Confirm (' +str_message+ ') ==true) {document.forms (0). " +btn+ ". Click ();} </script> ");
}

38. Overload confirmation dialog box, click OK to trigger a hidden button event, click Cancel to trigger a hidden button event


/**////<summary>
Server-side Pop-up Confirm dialog box asking users to turn to those actions, including "OK" and "Cancel" actions
</summary>
<param name= "Str_message" > hint information, such as: "Successfully add data, click \ OK \" button to fill in the process, click \ cancel \ "Modify Data" </param>
<param name= "Btn_redirect_flow" > "OK" button ID value </param>
<param name= "btn_redirect_self" > "Cancel" button ID value </param>
<param name= "page" >page class </param>
public void Confirm (string str_message,string btn_redirect_flow,string btn_redirect_self,page Page)
{
Page. RegisterStartupScript ("", "<script> If" (Confirm (' +str_message+ ') ==true) {document.forms (0). " +btn_redirect_flow+ ". Click ();} Else{document.forms (0). " +btn_redirect_self+ ". Click ();} </script> ");
}

39. Get Focus


/**////<summary>
To have the control focus
</summary>
<param name= "Str_ctl_name" > Get focus Control ID values, such as:txt_name</param>
<param name= "page" >page class </param>
public void GetFocus (String str_ctl_name,page Page)
{
Page. RegisterStartupScript ("", "<script>document.forms (0)." +str_ctl_name+ ". focus (); Document.forms (0). " +str_ctl_name+ ". Select ();</script>");
}

40. Subform returns to main form


/**////<summary>
Name: redirect
Function: Subform returns to main form
Parameters: URL
return value: null
</summary>
public void Redirect (String url,page Page)
{
if (session["Ifdefault"]!= (object) "Default")
{
Page. RegisterStartupScript ("", "<script>window.top.document.location.href=" "+url+" ";</script>");
}
}


41. Determining whether a number


/**////<summary>
Name: Isnumberic
Function: To determine whether the input is a number
Parameters: String Otext: Source text
return value: BOOL true: Yes false: No
</summary>

public bool Isnumberic (string otext)
{
Try
{
int Var1=convert.toint32 (otext);
return true;
}
Catch
{
return false;
}
}

Gets the actual length of the string (including Chinese characters)

Gets the actual length of the string ostring
public int Stringlength (string ostring)
{
Byte[] Strarray=system.text. Encoding.default. GetBytes (ostring);
int res=strarray.length;
return res;
}

42. Convert Carriage return to tab


When you hit enter on a control with a KeyDown event, it changes to tab
public void Tab (system.web. Ui. WebControls. WebControl WebControl)
{
WebControl. Attributes. ADD ("onkeyDown", "if (event.keycode==13) event.keycode=9");
}

43.datagrid Paging if the index is exceeded when deleted


public void Jumppage (System.Web.UI.WebControls.DataGrid dg)
{
int int_pageless;//define page Jump pages
// If the current page is the last page
if (DG. CurrentPageIndex = DG. PageCount-1)
{
//If there is only one page
if (DG. CurrentPageIndex = = 0
{
///Delete after page stop on current page
DG. CurrentPageIndex = DG. PageCount-1;
}
Else
{
//If the last page has only one record
if (DG. Items.Count% DG. PageSize = 1) | | Dg. PageSize = = 1
{
//When the last record of the last page is deleted, the page should jump to the previous page
Int_pageless = 2;
}
Else//If the number of records on the last page is greater than 1, then the current page
{
Int_pageless = 1 is still stopped on the last page after the record is deleted;
}
DG. CurrentPageIndex = DG. pagecount-int_pageless;
}
}
}

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.