ASP.NET程序中常用的三十三种代码(二)
17.数字格式化
A.以下正确的输入格式: [2004-2-29], [2004-02-29 10:29:39 pm], [2004/12/31]
Application_Start()事件中
添加Application[属性名] = xxx;
就是你的全局变量
20.怎样作到HyperLinkColumn生成的连接后,点击连接,打开新窗口?
HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank")
【ASPNETMENU】点击菜单项弹出新窗口
在你的menuData.xml文件的菜单项中加入URLTarget="_blank",
21.读取DataGrid控件TextBox值
1.1 取当前年月日时分秒
添加删除确认:
【<%#Container.DataItem("price")%>的结果是500.0000,怎样格式化为500.00?】
<%#Container.DataItem("price","{0:¥#,##0.00}")%>
int i=123456;
string s=i.ToString("###,###.00");
18.日期格式化
<%#Container.DataItem("price","{0:¥#,##0.00}")%>
int i=123456;
string s=i.ToString("###,###.00");
1 【aspx页面内:<%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date")%>
2 显示为: 2004-8-11 19:44:28
我只想要:2004-8-11 】
2 显示为: 2004-8-11 19:44:28
1 <%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}")%>
【格式化日期】
1 object((DateTime)objectFromDB).ToString("yyyy-MM-dd");
【日期的验证表达式】A.以下正确的输入格式: [2004-2-29], [2004-02-29 10:29:39 pm], [2004/12/31]
1 ^((\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})))?$
2
B.以下正确的输入格式:[0001-12-31], [9999 09 30], [2002/03/03]
2
1 ^\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]))$
【大小写转换】
1 HttpUtility.HtmlEncode(string);
2 HttpUtility.HtmlDecode(string)
19.如何设定全局变量Global.asax中2 HttpUtility.HtmlDecode(string)
Application_Start()事件中
添加Application[属性名] = xxx;
就是你的全局变量
20.怎样作到HyperLinkColumn生成的连接后,点击连接,打开新窗口?
HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank")
【ASPNETMENU】点击菜单项弹出新窗口
在你的menuData.xml文件的菜单项中加入URLTarget="_blank",
1 <?xml version="1.0" encoding="GB2312"?>
2 <MenuData ImagesBaseURL="images/">
3 <MenuGroup>
4 <MenuItem Label="内参信息" URL="Infomation.aspx" >
5 <MenuGroup ID="BBC">
6 <MenuItem Label="公告信息" URL="Infomation.aspx" URLTarget="_blank" LeftIcon="file.gif"/>
7 <MenuItem Label="编制信息简报" URL="NewInfo.aspx" LeftIcon="file.gif" />
8
最好将你的aspnetmenu升级到1.2版2 <MenuData ImagesBaseURL="images/">
3 <MenuGroup>
4 <MenuItem Label="内参信息" URL="Infomation.aspx" >
5 <MenuGroup ID="BBC">
6 <MenuItem Label="公告信息" URL="Infomation.aspx" URLTarget="_blank" LeftIcon="file.gif"/>
7 <MenuItem Label="编制信息简报" URL="NewInfo.aspx" LeftIcon="file.gif" />
8
21.读取DataGrid控件TextBox值
1 foreach(DataGrid dgi in yourDataGrid.Items)
2 {
3 TextBox tb = (TextBox)dgi.FindControl("yourTextBoxId");
4 tb.Text.
5 }
23.在DataGrid中有3个模板列包含Textbox分别为 DG_ShuLiang (数量) DG_DanJian(单价) DG_JinE(金额)分别在5.6.7列,要求在录入数量及单价的时候自动算出金额即:数量*单价=金额还要求录入时限制为数值型.我如何用客户端脚本实现这个功能?2 {
3 TextBox tb = (TextBox)dgi.FindControl("yourTextBoxId");
4 tb.Text.
5 }
1 <asp:TemplateColumn HeaderText="数量">
2 <ItemTemplate>
3 <asp:TextBox id="ShuLiang" runat='server' Text='<%# DataBinder.Eval(Container.DataItem,"DG_ShuLiang")%>'
4 onkeyup="javascript:DoCal()"
5 />
6
7 <asp:RegularExpressionValidator id="revS" runat="server" ControlToValidate="ShuLiang" ErrorMessage="must be integer" ValidationExpression="^\d+$" />
8 </ItemTemplate>
9 </asp:TemplateColumn>
10
11 <asp:TemplateColumn HeaderText="单价">
12 <ItemTemplate>
13 <asp:TextBox id="DanJian" runat='server' Text='<%# DataBinder.Eval(Container.DataItem,"DG_DanJian")%>'
14 onkeyup="javascript:DoCal()"
15 />
16
17 <asp:RegularExpressionValidator id="revS2" runat="server" ControlToValidate="DanJian" ErrorMessage="must be numeric" ValidationExpression="^\d+(\.\d*)?$" />
18
19 </ItemTemplate>
20 </asp:TemplateColumn>
21
22 <asp:TemplateColumn HeaderText="金额">
23 <ItemTemplate>
24 <asp:TextBox id="JinE" runat='server' Text='<%# DataBinder.Eval(Container.DataItem,"DG_JinE")%>' />
25 </ItemTemplate>
26 </asp:TemplateColumn><script language="javascript">
27 function DoCal()
28 {
29 var e = event.srcElement;
30 var row = e.parentNode.parentNode;
31 var txts = row.all.tags("INPUT");
32 if (!txts.length || txts.length < 3)
33 return;
34
35 var q = txts[txts.length-3].value;
36 var p = txts[txts.length-2].value;
37
38 if (isNaN(q) || isNaN(p))
39 return;
40
41 q = parseInt(q);
42 p = parseFloat(p);
43
44 txts[txts.length-1].value = (q * p).toFixed(2);
45 }
46 </script>
47
24.datagrid选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看不到了。
2 <ItemTemplate>
3 <asp:TextBox id="ShuLiang" runat='server' Text='<%# DataBinder.Eval(Container.DataItem,"DG_ShuLiang")%>'
4 onkeyup="javascript:DoCal()"
5 />
6
7 <asp:RegularExpressionValidator id="revS" runat="server" ControlToValidate="ShuLiang" ErrorMessage="must be integer" ValidationExpression="^\d+$" />
8 </ItemTemplate>
9 </asp:TemplateColumn>
10
11 <asp:TemplateColumn HeaderText="单价">
12 <ItemTemplate>
13 <asp:TextBox id="DanJian" runat='server' Text='<%# DataBinder.Eval(Container.DataItem,"DG_DanJian")%>'
14 onkeyup="javascript:DoCal()"
15 />
16
17 <asp:RegularExpressionValidator id="revS2" runat="server" ControlToValidate="DanJian" ErrorMessage="must be numeric" ValidationExpression="^\d+(\.\d*)?$" />
18
19 </ItemTemplate>
20 </asp:TemplateColumn>
21
22 <asp:TemplateColumn HeaderText="金额">
23 <ItemTemplate>
24 <asp:TextBox id="JinE" runat='server' Text='<%# DataBinder.Eval(Container.DataItem,"DG_JinE")%>' />
25 </ItemTemplate>
26 </asp:TemplateColumn><script language="javascript">
27 function DoCal()
28 {
29 var e = event.srcElement;
30 var row = e.parentNode.parentNode;
31 var txts = row.all.tags("INPUT");
32 if (!txts.length || txts.length < 3)
33 return;
34
35 var q = txts[txts.length-3].value;
36 var p = txts[txts.length-2].value;
37
38 if (isNaN(q) || isNaN(p))
39 return;
40
41 q = parseInt(q);
42 p = parseFloat(p);
43
44 txts[txts.length-1].value = (q * p).toFixed(2);
45 }
46 </script>
47
1 page_load
2 page.smartNavigation=true
25.在Datagrid中修改数据,当点击编辑键时,数据出现在文本框中,怎么控制文本框的大小 ?2 page.smartNavigation=true
1 private void DataGrid1_ItemDataBound(obj sender,DataGridItemEventArgs e)
2 {
3 for(int i=0;i<e.Item.Cells.Count-1;i++)
4 if(e.Item.ItemType==ListItemType.EditType)
5 {
6 e.Item.Cells[i].Attributes.Add("Width", "80px")
7 }
8 }
26.对话框
2 {
3 for(int i=0;i<e.Item.Cells.Count-1;i++)
4 if(e.Item.ItemType==ListItemType.EditType)
5 {
6 e.Item.Cells[i].Attributes.Add("Width", "80px")
7 }
8 }
1 private static string ScriptBegin = "<script language=\"JavaScript\">";
2 private static string ScriptEnd = "</script>";
3
4 public static void ConfirmMessageBox(string PageTarget,string Content)
5 {
6 string ConfirmContent="var retValue=window.confirm('"+Content+"');"+"if(retValue){window.location='"+PageTarget+"';}";
7
8 ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;
9
10 Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler;
11 ParameterPage.RegisterStartupScript("confirm",ConfirmContent);
12 //Response.Write(strScript);
13 }
14
27. 将时间格式化:string aa=DateTime.Now.ToString("yyyy年MM月dd日");2 private static string ScriptEnd = "</script>";
3
4 public static void ConfirmMessageBox(string PageTarget,string Content)
5 {
6 string ConfirmContent="var retValue=window.confirm('"+Content+"');"+"if(retValue){window.location='"+PageTarget+"';}";
7
8 ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;
9
10 Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler;
11 ParameterPage.RegisterStartupScript("confirm",ConfirmContent);
12 //Response.Write(strScript);
13 }
14
1.1 取当前年月日时分秒
1 currentTime=System.DateTime.Now;
1.2 取当前年
1 int 年= DateTime.Now.Year;
1.3 取当前月
1 int 月= DateTime.Now.Month;
2
1.4 取当前日
2
1 int 日= DateTime.Now.Day;
1.5 取当前时
1 int 时= DateTime.Now.Hour;
1.6 取当前分1 int 分= DateTime.Now.Minute;
28.自定义分页代码:
1 public static int pageCount; //总页面数
2 public static int curPageIndex=1; //当前页面
3 下一页:
4 if(DataGrid1.CurrentPageIndex < (DataGrid1.PageCount - 1))
5 {
6 DataGrid1.CurrentPageIndex += 1;
7 curPageIndex+=1;
8 }
9 bind(); // DataGrid1数据绑定函数
10 上一页:
11 if(DataGrid1.CurrentPageIndex >0)
12 {
13 DataGrid1.CurrentPageIndex += 1;
14 curPageIndex-=1;
15 }
16 bind(); // DataGrid1数据绑定函数
17 直接页面跳转:
18 int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值
19
20 if(a<DataGrid1.PageCount)
21 {
22 this.DataGrid1.CurrentPageIndex=a;
23 }
24 bind();
29.DataGrid使用:2 public static int curPageIndex=1; //当前页面
3 下一页:
4 if(DataGrid1.CurrentPageIndex < (DataGrid1.PageCount - 1))
5 {
6 DataGrid1.CurrentPageIndex += 1;
7 curPageIndex+=1;
8 }
9 bind(); // DataGrid1数据绑定函数
10 上一页:
11 if(DataGrid1.CurrentPageIndex >0)
12 {
13 DataGrid1.CurrentPageIndex += 1;
14 curPageIndex-=1;
15 }
16 bind(); // DataGrid1数据绑定函数
17 直接页面跳转:
18 int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值
19
20 if(a<DataGrid1.PageCount)
21 {
22 this.DataGrid1.CurrentPageIndex=a;
23 }
24 bind();
添加删除确认:
1 private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
2 {
3 foreach(DataGridItem di in this.DataGrid1.Items)
4 {
5 if(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)
6 {
7 ((LinkButton)di.Cells[8].Controls[0]).Attributes.Add("onclick","return confirm('确认删除此项吗?');");
8 }
9 }
10 }
样式交替:
2 {
3 foreach(DataGridItem di in this.DataGrid1.Items)
4 {
5 if(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)
6 {
7 ((LinkButton)di.Cells[8].Controls[0]).Attributes.Add("onclick","return confirm('确认删除此项吗?');");
8 }
9 }
10 }
1 ListItemType itemType = e.Item.ItemType;
2
3 if (itemType == ListItemType.Item )
4 {
5 e.Item.Attributes["onmouseout"] = "javascript:this.style.backgroundColor='#FFFFFF';";
6 e.Item.Attributes["onmouseover"] = "javascript:this.style.backgroundColor='#d9ece1';cursor='hand';" ;
7 }
8 else if( itemType == ListItemType.AlternatingItem)
9 {
10 e.Item.Attributes["onmouseout"] = "javascript:this.style.backgroundColor='#a0d7c4';";
11 e.Item.Attributes["onmouseover"] = "javascript:this.style.backgroundColor='#d9ece1';cursor='hand';" ;
12 }
添加一个编号列:
2
3 if (itemType == ListItemType.Item )
4 {
5 e.Item.Attributes["onmouseout"] = "javascript:this.style.backgroundColor='#FFFFFF';";
6 e.Item.Attributes["onmouseover"] = "javascript:this.style.backgroundColor='#d9ece1';cursor='hand';" ;
7 }
8 else if( itemType == ListItemType.AlternatingItem)
9 {
10 e.Item.Attributes["onmouseout"] = "javascript:this.style.backgroundColor='#a0d7c4';";
11 e.Item.Attributes["onmouseover"] = "javascript:this.style.backgroundColor='#d9ece1';cursor='hand';" ;
12 }
1 DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable
2 DataColumn dc=dt.Columns.Add("number",System.Type.GetType("System.String"));
3
4 for(int i=0;i<dt.Rows.Count;i++)
5 {
6 dt.Rows[i]["number"]=(i+1).ToString();
7 }
8
9 DataGrid1.DataSource=dt;
10 DataGrid1.DataBind();
DataGrid1中添加一个CheckBox,页面中添加一个全选框2 DataColumn dc=dt.Columns.Add("number",System.Type.GetType("System.String"));
3
4 for(int i=0;i<dt.Rows.Count;i++)
5 {
6 dt.Rows[i]["number"]=(i+1).ToString();
7 }
8
9 DataGrid1.DataSource=dt;
10 DataGrid1.DataBind();
1 private void CheckBox2_CheckedChanged(object sender, System.EventArgs e)
2 {
3 foreach(DataGridItem thisitem in DataGrid1.Items)
4 {
5 ((CheckBox)thisitem.Cells[0].Controls[1]).Checked=CheckBox2.Checked;
6 }
7 }
将当前页面中DataGrid1显示的数据全部删除
2 {
3 foreach(DataGridItem thisitem in DataGrid1.Items)
4 {
5 ((CheckBox)thisitem.Cells[0].Controls[1]).Checked=CheckBox2.Checked;
6 }
7 }
1 foreach(DataGridItem thisitem in DataGrid1.Items)
2 {
3 if(((CheckBox)thisitem.Cells[0].Controls[1]).Checked)
4 {
5 string strloginid= DataGrid1.DataKeys[thisitem.ItemIndex].ToString();
6 Del (strloginid); //删除函数
7 }
8 }
30.当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在Web.config,然后在Global.asax中初始化)
2 {
3 if(((CheckBox)thisitem.Cells[0].Controls[1]).Checked)
4 {
5 string strloginid= DataGrid1.DataKeys[thisitem.ItemIndex].ToString();
6 Del (strloginid); //删除函数
7 }
8 }
1 Application["ConnStr"]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.
2 AppSettings["ConnStr"].ToString();
31. 变量.ToString()
2 AppSettings["ConnStr"].ToString();
1 12345.ToString("n"); //生成 12,345.00
2 12345.ToString("C"); //生成 ¥12,345.00
3 12345.ToString("e"); //生成 1.234500e+004
4 12345.ToString("f4"); //生成 12345.0000
5 12345.ToString("x"); //生成 3039 (16进制)
6 12345.ToString("p"); //生成 1,234,500.00%
32、变量.Substring(参数1,参数2);2 12345.ToString("C"); //生成 ¥12,345.00
3 12345.ToString("e"); //生成 1.234500e+004
4 12345.ToString("f4"); //生成 12345.0000
5 12345.ToString("x"); //生成 3039 (16进制)
6 12345.ToString("p"); //生成 1,234,500.00%
截取字串的一部分,参数1为左起始位数,参数2为截取几位。 如:string s1 = str.Substring(0,2);
33.在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个FORM,这时可以导向另外一个页面再提交登陆信息)
1 <SCRIPT language="javascript">
2 <!--
3 function gook(pws)
4 {
5 frm.submit();
6 }
7 //-->
8
9 </SCRIPT> <body leftMargin="0" topMargin="0" onload="javascript:gook()" marginwidth="0" marginheight="0">
10 <form name="frm" action=" http://220.194.55.68:6080/login.php?retid=7259 " method="post">
11 <tr>
12 <td>
13 <input id="f_user" type="hidden" size="1" name="f_user" runat="server">
14 <input id="f_domain" type="hidden" size="1" name="f_domain" runat="server">
15 <input class="box" id="f_pass" type="hidden" size="1" name="pwshow" runat="server">
16
17 <INPUT id="lng" type="hidden" maxLength="20" size="1" value="5" name="lng">
18 <INPUT id="tem" type="hidden" size="1" value="2" name="tem">
19 </td>
20 </tr>
21 </from>
22
23
文本框的名称必须是你要登陆的网页上的名称,如果源码不行可以用vsniffer 看看下面是获取用户输入的登陆信息的代码:
2 <!--
3 function gook(pws)
4 {
5 frm.submit();
6 }
7 //-->
8
9 </SCRIPT> <body leftMargin="0" topMargin="0" onload="javascript:gook()" marginwidth="0" marginheight="0">
10 <form name="frm" action=" http://220.194.55.68:6080/login.php?retid=7259 " method="post">
11 <tr>
12 <td>
13 <input id="f_user" type="hidden" size="1" name="f_user" runat="server">
14 <input id="f_domain" type="hidden" size="1" name="f_domain" runat="server">
15 <input class="box" id="f_pass" type="hidden" size="1" name="pwshow" runat="server">
16
17 <INPUT id="lng" type="hidden" maxLength="20" size="1" value="5" name="lng">
18 <INPUT id="tem" type="hidden" size="1" value="2" name="tem">
19 </td>
20 </tr>
21 </from>
22
23
1 string name;
2 name=Request.QueryString["EmailName"];
3
4 try
5 {
6 int a=name.IndexOf("@",0,name.Length);
7 f_user.Value=name.Substring(0,a);
8 f_domain.Value=name.Substring(a+1,name.Length-(a+1));
9 f_pass.Value=Request.QueryString["Psw"];
10 }
11
12 catch
13 {
14 Script.Alert("错误的邮箱!");
15 Server.Transfer("index.aspx");
16 }
17
2 name=Request.QueryString["EmailName"];
3
4 try
5 {
6 int a=name.IndexOf("@",0,name.Length);
7 f_user.Value=name.Substring(0,a);
8 f_domain.Value=name.Substring(a+1,name.Length-(a+1));
9 f_pass.Value=Request.QueryString["Psw"];
10 }
11
12 catch
13 {
14 Script.Alert("错误的邮箱!");
15 Server.Transfer("index.aspx");
16 }
17