欢迎光临
我们一直在努力

ASP.NET常用代码-.NET教程,Asp.Net开发

建站超值云服务器,限时71元/月

1. 打开新的窗口并传送参数:
传送参数:
response.write(“<script>window.open(*.aspx?id=”+this.dropdownlist1.selectindex+”&id1=”+…+”)</script>”)

接收参数:
string a = request.querystring(“id”);
string b = request.querystring(“id1”);

2.为按钮添加对话框

传送参数:
response.write(“<script>window.open(*.aspx?id=”+this.dropdownlist1.selectindex+”&id1=”+…+”)</script>”)

接收参数:
string a = request.querystring(“id”);
string b = request.querystring(“id1”);

2.为按钮添加对话框

button1.attributes.add(“onclick”,”return confirm(确认?)”);

button.attributes.add(“onclick”,”if(confirm(are you sure…?)){return true;}else{return false;}”)

3.删除表格选定记录

int intempid = (int)mydatagrid.datakeys[e.item.itemindex];
string deletecmd = “delete from employee where emp_id = ” + intempid.tostring()

4.删除表格记录警告
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(您是否确定要删除这条信息);”);
break;
default:
break;
}

}

5.点击表格行链接另一页

private void grdcustomer_itemdatabound(object sender, system.web.ui.webcontrols.datagriditemeventargs e)
{
//点击表格打开
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 + “);”);
}

双击表格连接到另一页
在itemdatabind事件中
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 + “”);
}
双击表格打开新一页
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 + “)”);
}
★特别注意:【?id=】 处不能为 【?id =】

6.表格超连接列传递参数
<asp:hyperlinkcolumn target=”_blank” headertext=”id号” datatextfield=”id” navigateurl=”aaa.aspx?id=<%# databinder.eval(container.dataitem, “数据字段1”)%> & name=<%# databinder.eval(container.dataitem, “数据字段2”)%> />

7.表格点击改变颜色
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;”);
}

写在datagrid的_itemdatabound里
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.关于日期格式

日期格式设定
dataformatstring=”{0:yyyy-mm-dd}”

我觉得应该在itembound事件中
e.items.cell[“你的列”].text=datetime.parse(e.items.cell[“你的列”].text.tostring(“yyyy-mm-dd”))

9.获取错误信息并到指定页面
不要使用response.redirect,而应该使用server.transfer
e.g
// in global.asax
protected void application_error(object sender, eventargs e) {
if (server.getlasterror() is httpunhandledexception)
server.transfer(“myerrorpage.aspx”);

//其余的非httpunhandledexception异常交给asp.net自己处理就okay了 🙂
}

redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理

10.清空cookie
cookie.expires=[datetime];
response.cookies(“username”).expires = 0

11.自定义异常处理

//自定义异常处理类
using system;
using system.diagnostics;

namespace myappexception
{
/// <summary>
/// 从系统异常类applicationexception继承的应用程序异常处理类。
/// 自动将异常内容记录到windows nt/2000的应用程序日志
/// </summary>
public class appexception:system.applicationexception
{
public appexception()
{
if (applicationconfiguration.eventlogenabled)
logevent(“出现一个未知错误。”);
}

public appexception(string message)
{
logevent(message);
}

public appexception(string message,exception innerexception)
{
logevent(message);
if (innerexception != null)
{
logevent(innerexception.message);
}
}

//日志记录类
using system;
using system.configuration;
using system.diagnostics;
using system.io;
using system.text;
using system.threading;

namespace myeventlog
{
/// <summary>
/// 事件日志记录类,提供事件日志记录支持
/// <remarks>
/// 定义了4个日志记录方法 (error, warning, info, trace)
/// </remarks>
/// </summary>
public class applicationlog
{
/// <summary>
/// 将错误信息记录到win2000/nt事件日志中
/// <param name=”message”>需要记录的文本信息</param>
/// </summary>
public static void writeerror(string message)
{

writelog(tracelevel.error, message);
}

/// <summary>
/// 将警告信息记录到win2000/nt事件日志中
/// <param name=”message”>需要记录的文本信息</param>
/// </summary>
public static void writewarning(string message)
{

writelog(tracelevel.warning, message);
}

/// <summary>
/// 将提示信息记录到win2000/nt事件日志中
/// <param name=”message”>需要记录的文本信息</param>
/// </summary>
public static void writeinfo(string message)
{
writelog(tracelevel.info, message);
}
/// <summary>
/// 将跟踪信息记录到win2000/nt事件日志中
/// <param name=”message”>需要记录的文本信息</param>
/// </summary>
public static void writetrace(string message)
{

writelog(tracelevel.verbose, message);
}

/// <summary>
/// 格式化记录到事件日志的文本信息格式
/// <param name=”ex”>需要格式化的异常对象</param>
/// <param name=”catchinfo”>异常信息标题字符串.</param>
/// <retvalue>
/// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</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>
/// 实际事件日志写入方法
/// <param name=”level”>要记录信息的级别(error,warning,info,trace).</param>
/// <param name=”messagetext”>要记录的文本.</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.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 );
//写入事件日志
eventlog.writeentry(messagetext, logentrytype);

}
catch {} //忽略任何异常
}
} //class applicationlog
}

12.panel 横向滚动,纵向自动扩展
<asp:panel style=”overflow-x:scroll;overflow-y:auto;”></asp:panel>

13.回车转换成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超级连接列
datanavigateurlfield=”字段名” datanavigateurlformatstring=”http://xx/inc/delete.aspx?id={0}”

15.datagrid行随鼠标变色
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.模板列
<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=”选中”>
<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>

后台代码

protected void checkall_checkedchanged(object sender, system.eventargs e)
{
//改变列的选定,实现全选或全不选。
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.数字格式化
【<%#container.dataitem(“price”)%>的结果是500.0000,怎样格式化为500.00?】

<%#container.dataitem(“price”,”{0:¥#,##0.00}”)%>

int i=123456;
string s=i.tostring(“###,###.00”);

18.日期格式化

【aspx页面内:<%# databinder.eval(container.dataitem,”company_ureg_date”)%>
显示为: 2004-8-11 19:44:28
我只想要:2004-8-11 】

<%# databinder.eval(container.dataitem,”company_ureg_date”,”{0:yyyy-m-d}”)%>

应该如何改?

【格式化日期】
取出来,一般是object
((datetime)objectfromdb).tostring(“yyyy-mm-dd”);

【日期的验证表达式】
a.以下正确的输入格式: [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.以下正确的输入格式:[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]))$

【大小写转换】

httputility.htmlencode(string);
httputility.htmldecode(string)

19.如何设定全局变量
global.asax中

application_start()事件中

添加application[属性名] = xxx;

就是你的全局变量

20.怎样作到hyperlinkcolumn生成的连接后,点击连接,打开新窗口?

hyperlinkcolumn有个属性target,将器值设置成”_blank”即可.(target=”_blank”)

【aspnetmenu】点击菜单项弹出新窗口
在你的menudata.xml文件的菜单项中加入urltarget=”_blank”
如:
<?xml version=”1.0″ encoding=”gb2312″?>
<menudata imagesbaseurl=”images/”>
<menugroup>
<menuitem label=”内参信息” url=”infomation.aspx” >
<menugroup id=”bbc”>
<menuitem label=”公告信息” url=”infomation.aspx” urltarget=”_blank” lefticon=”file.gif”/>
<menuitem label=”编制信息简报” url=”newinfo.aspx” lefticon=”file.gif” />
……
最好将你的aspnetmenu升级到1.2版

21.委托讨论
http://community.csdn.net/expert/topic/2651/2651579.xml?temp=.7183191
http://dev.csdn.net/develop/article/22/22951.shtm

22.读取datagrid控件textbox值

foreach(datagrid dgi in yourdatagrid.items)
{
textbox tb = (textbox)dgi.findcontrol(“yourtextboxid”);
tb.text….
}

23.在datagrid中有3个模板列包含textbox分别为 dg_shuliang (数量) dg_danjian(单价) dg_jine(金额)分别在5.6.7列,要求在录入数量及单价的时候自动算出金额即:数量*单价=金额还要求录入时限制为 数值型.我如何用客户端脚本实现这个功能?

〖思归〗
<asp:templatecolumn headertext=”数量”>
<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=”单价”>
<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=”金额”>
<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>

24.datagrid选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看不到了
page_load
page.smartnavigation=true

25.在datagrid中修改数据,当点击编辑键时,数据出现在文本框中,怎么控制文本框的大小 ?

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.对话框
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. 将时间格式化:string aa=datetime.now.tostring(“yyyy年mm月dd日”);

1.1 取当前年月日时分秒
currenttime=system.datetime.now;

1.2 取当前年
int 年= datetime.now.year;

1.3 取当前月
int 月= datetime.now.month;

1.4 取当前日
int 日= datetime.now.day;

1.5 取当前时
int 时= datetime.now.hour;

1.6 取当前分
int 分= datetime.now.minute;

1.7 取当前秒
int 秒= datetime.now.second;

1.8 取当前毫秒
int 毫秒= datetime.now.millisecond;

28.自定义分页代码:

先定义变量 :public static int pagecount; //总页面数

public static int curpageindex=1; //当前页面

下一页:

if(datagrid1.currentpageindex < (datagrid1.pagecount – 1))

{

datagrid1.currentpageindex += 1;

curpageindex+=1;

}

bind(); // datagrid1数据绑定函数

上一页:

if(datagrid1.currentpageindex >0)

{

datagrid1.currentpageindex += 1;

curpageindex-=1;

}

bind(); // datagrid1数据绑定函数

直接页面跳转:

int a=int.parse(jumppage.value.trim());//jumppage.value.trim()为跳转值

if(a<datagrid1.pagecount)

{

this.datagrid1.currentpageindex=a;

}

bind();

29.datagrid使用:

3.1添加删除确认:

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(确认删除此项吗?);”);

}

}

}

3.2样式交替:

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添加一个编号列:

datatable dt= c.executertntableforaccess(sqltxt); //执行sql返回的datatable

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中添加一个checkbox,页面中添加一个全选框

private void checkbox2_checkedchanged(object sender, system.eventargs e)

{

foreach(datagriditem thisitem in datagrid1.items)

{

((checkbox)thisitem.cells[0].controls[1]).checked=checkbox2.checked;

}

}

将当前页面中datagrid1显示的数据全部删除

foreach(datagriditem thisitem in datagrid1.items)

{

if(((checkbox)thisitem.cells[0].controls[1]).checked)

{

string strloginid= datagrid1.datakeys[thisitem.itemindex].tostring();

del (strloginid); //删除函数

}

}

30.当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在web.config,然后在global.asax中初始化)

在application_start中添加以下代码:

application[“connstr”]=this.context.request.physicalapplicationpath+configurationsettings.appsettings[“connstr”].tostring();

31. 变量.tostring()
字符型转换 转为字符串
12345.tostring(“n”); //生成 12,345.00
12345.tostring(“c”); //生成 ¥12,345.00
12345.tostring(“e”); //生成 1.234500e+004
12345.tostring(“f4”); //生成 12345.0000
12345.tostring(“x”); //生成 3039 (16进制)
12345.tostring(“p”); //生成 1,234,500.00%

32、变量.substring(参数1,参数2);
截取字串的一部分,参数1为左起始位数,参数2为截取几位。
如:string s1 = str.substring(0,2);

34.在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个form,这时可以导向另外一个页面再提交登陆信息)

<script language=”javascript”>
<!–
 function gook(pws)
 {
  frm.submit();
 }
//–>

</script> <body leftmargin=”0″ topmargin=”0″ onload=”javascript:gook()” marginwidth=”0″ marginheight=”0″>
<form name=”frm” action=” http://220.194.55.68:6080/login.php?retid=7259 ” method=”post”>
<tr>
<td>
<input id=”f_user” type=”hidden” size=”1″ name=”f_user” runat=”server”>
<input id=”f_domain” type=”hidden” size=”1″ name=”f_domain” runat=”server”>
<input class=”box” id=”f_pass” type=”hidden” size=”1″ name=”pwshow” runat=”server”>

<input id=”lng” type=”hidden” maxlength=”20″ size=”1″ value=”5″ name=”lng”>
<input id=”tem” type=”hidden” size=”1″ value=”2″ name=”tem”>

</td>

</tr>

</form>

文本框的名称必须是你要登陆的网页上的名称,如果源码不行可以用vsniffer 看看。
  下面是获取用户输入的登陆信息的代码:

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(“错误的邮箱!”);
 server.transfer(“index.aspx”);
}

35.警告窗口

/**//// <summary>
/// 服务器端弹出alert对话框
/// </summary>
/// <param name=”str_message”>提示信息,例子:”不能为空!”</param>
/// <param name=”page”>page类</param>
public void alert(string str_message,page page)
{
page.registerstartupscript(“”,”<script>alert(“+str_message+”);</script>”);
}

36.重载此警告窗口,使某控件获得焦点

/**//// <summary>
/// 服务器端弹出alert对话框,并使控件获得焦点
/// </summary>
/// <param name=”str_ctl_name”>获得焦点控件id值,比如:txt_name</param>
/// <param name=”str_message”>提示信息,例子:”请输入您姓名!”</param>
/// <param name=”page”>page类</param>
public void alert(string str_ctl_name,string str_message,page page)
{
page.registerstartupscript(“”,”<script>alert(“+str_message+”);document.forms(0).”+str_ctl_name+”.focus(); document.forms(0).”+str_ctl_name+”.select();</script>”);
}

37.确认对话框

/**//// <summary>
/// 服务器端弹出confirm对话框
/// </summary>
/// <param name=”str_message”>提示信息,例子:”您是否确认删除!”</param>
/// <param name=”btn”>隐藏botton按钮id值,比如:btn_flow</param>
/// <param name=”page”>page类</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.重载确认对话框,点击确定触发一个隐藏按钮事件,点击取消触发一个隐藏按钮事件

/**//// <summary>
/// 服务器端弹出confirm对话框,询问用户准备转向那些操作,包括“确定”和“取消”时的操作
/// </summary>
/// <param name=”str_message”>提示信息,比如:”成功增加数据,单击\”确定\”按钮填写流程,单击\”取消\”修改数据”</param>
/// <param name=”btn_redirect_flow”>”确定”按钮id值</param>
/// <param name=”btn_redirect_self”>”取消”按钮id值</param>
/// <param name=”page”>page类</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.获得焦点

/**//// <summary>
/// 使控件获得焦点
/// </summary>
/// <param name=”str_ctl_name”>获得焦点控件id值,比如:txt_name</param>
/// <param name=”page”>page类</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.子窗体返回主窗体

/**////<summary>
///名称:redirect
///功能:子窗体返回主窗体
///参数:url
///返回值:空
///</summary>
public void redirect(string url,page page)
{
if ( session[“ifdefault”]!=(object)”default”)
{
page.registerstartupscript(“”,”<script>window.top.document.location.href=”+url+”;</script>”);
}
}

41.判断是否为数字

/**//// <summary>
/// 名称:isnumberic
/// 功能:判断输入的是否是数字
/// 参数:string otext:源文本
/// 返回值: bool true:是 false:否
/// </summary>

public bool isnumberic(string otext)
{
try
{
int var1=convert.toint32 (otext);
return true;
}
catch
{
return false;
}
}

获得字符串实际长度(包括中文字符)

//获得字符串ostring的实际长度
public int stringlength(string ostring)
{
byte[] strarray=system.text .encoding.default .getbytes (ostring);
int res=strarray.length ;
return res;
}

42.将回车转换为tab

//当在有keydown事件的控件上敲回车时,变为tab
public void tab(system.web .ui.webcontrols .webcontrol webcontrol)
{
webcontrol.attributes .add (“onkeydown”, “if(event.keycode==13) event.keycode=9”);
}

43.datagrid分页中如果删除时出现超出索引

public void jumppage(system.web.ui.webcontrols.datagrid dg)
{
int int_pageless; //定义页面跳转的页数
//如果当前页是最后一页
if(dg.currentpageindex == dg.pagecount-1)
{
//如果就只有一页
if(dg.currentpageindex == 0)
{
//删除后页面停在当前页
dg.currentpageindex = dg.pagecount-1;
}
else
{
//如果最后一页只有一条记录
if((dg.items.count % dg.pagesize == 1) || dg.pagesize == 1)
{
//把最后一页最后一条记录删除后,页面应跳转到前一页
int_pageless = 2;
}
else //如果最后一页的记录数大于1,那么在最后一页删除记录后仍然停在当前页
{
int_pageless = 1;
}
dg.currentpageindex = dg.pagecount – int_pageless;
}
}
}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » ASP.NET常用代码-.NET教程,Asp.Net开发
分享到: 更多 (0)

相关推荐

  • 暂无文章