Hopes

Start Here..

 

Asp.net常用的51个代码(非常实用)

Asp.net常用的51个代码(非常实用) [复制链接]

51aspx


51Aspx


组别
超级管理员
生日
帖子
2197
论坛积分
4779 分
性别

注册时间
2007-05-17
1#
字体大小:


发表于 2007-06-10 00:50 |只看楼主
常用代码 asp.net
1.//弹出对话框.点击转向指定页面
Response.Write(&quot;<script>window.alert('该会员没有提交申请,请重新提交!')</script>&quot;);
Response.Write(&quot;<script>window.location ='http://www.51aspx.com/bizpulic/upmeb.aspx'</script>&quot;);
复制代码
2.//弹出对话框
Response.Write(&quot;<script language='javascript'>alert('产品添加成功!')</script >&quot;);
复制代码
3.//删除文件
string filename =&quot;20059595157517.jpg&quot;;
pub.util.DeleteFile(HttpContext.Current.Server.MapPath(&quot;../file/&quot;)+filename);
复制代码
4.//绑定下拉列表框datalist
System.Data.DataView dv=conn.Exec_ex(&quot;select -1 as code,'请选择经营模式' as content from dealin union select code,content from dealin&quot;);
this.dealincode.DataSource=dv;
this.dealincode.DataTextField=&quot;content&quot;;
this.dealincode.DataValueField=&quot;code&quot;;
this.dealincode.DataBind();
this.dealincode.Items.FindByValue(dv[0][&quot;dealincode&quot;].ToString()).Selected=true;
复制代码
5.//时间去秒显示
<%# System.DateTime.Parse(DataBinder.Eval(Container.DataItem,&quot;begtime&quot;).ToString()).ToShortDateString()%>
复制代码
6.//标题带链接
<%# &quot;<a class=\&quot;12c\&quot; target=\&quot;_blank\&quot; href=\&quot;http://www.51aspx/CV/_&quot;+DataBinder.Eval(Container.DataItem,&quot;procode&quot;)+&quot;.html\&quot;>&quot;+ DataBinder.Eval(Container.DataItem,&quot;proname&quot;)+&quot;</a>&quot;%>
复制代码
7.//修改转向
<%# &quot;<A href=\&quot;editpushpro.aspx?id=&quot;+DataBinder.Eval(Container.DataItem,&quot;code&quot;)+&quot;\&quot;>&quot;+&quot;修改&quot;+&quot;</A>&quot;%>
复制代码
8.//弹出确定按钮
<%# &quot;<A id=\&quot;btnDelete\&quot; onclick=\&quot;return confirm('你是否确定删除这条记录吗?');\&quot; href=\&quot;pushproduct.aspx?dl=&quot;+DataBinder.Eval(Container.DataItem,&quot;code&quot;)+&quot;\&quot;>&quot;+&quot;删除&quot;+&quot;</A>&quot;%>
复制代码
9.//输出数据格式化 "{0:F2}" 是格式 F2表示小数点后剩两位
<%# DataBinder.Eval(Container, &quot;DataItem.PriceMoney&quot;,&quot;{0:F2}&quot;) %>
复制代码
10.//提取动态网页内容
Uri uri = new Uri(&quot;http://www.51aspx.com/&quot;);
WebRequest req = WebRequest.Create(uri);
WebResponse resp = req.GetResponse();
Stream str = resp.GetResponseStream();
StreamReader sr = new StreamReader(str,System.Text.Encoding.Default);
string t = sr.ReadToEnd();
this.Response.Write(t.ToString());
复制代码
11.//获取" . "后面的字符
i.ToString().Trim().Substring(i.ToString().Trim().LastIndexOf(&quot;.&quot;)+1).ToLower().Trim()
复制代码
12. 打开新的窗口并传送参数:   传送参数:
response.write(&quot;<script>window.open(’*.aspx?id=&quot;+this.DropDownList1.SelectIndex+&quot;&amp;id1=&quot;+...+&quot;’)</script>&quot;)
复制代码
接收参数:
string a = Request.QueryString(&quot;id&quot;);
string b = Request.QueryString(&quot;id1&quot;);
复制代码
12.为按钮添加对话框
Button1.Attributes.Add(&quot;onclick&quot;,&quot;return confirm(’确认?’)&quot;);
button.attributes.add(&quot;onclick&quot;,&quot;if(confirm(’are you sure...?’)){return true;}else{return false;}&quot;)
复制代码
13.删除表格选定记录
int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex];
string deleteCmd = &quot;Delete from Employee where emp_id = &quot; + intEmpID.ToString()
复制代码
14.删除表格记录警告
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(&quot;onclick&quot;,&quot;return confirm(’您是否确定要删除这条信息’);&quot;);
break;
default:
break;
}
}
复制代码
15.点击表格行链接另一页
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(&quot;onclick&quot;,&quot;window.open(’Default.aspx?id=&quot; + e.Item.Cells[0].Text + &quot;’);&quot;);
}
复制代码
双击表格连接到另一页   在itemDataBind事件中
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string orderItemID =e.item.cells[1].Text;
e.item.Attributes.Add(&quot;ondblclick&quot;, &quot;location.href=’../ShippedGrid.aspx?id=&quot; + orderItemID + &quot;’&quot;);
}
复制代码
双击表格打开新一页
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string orderItemID =e.item.cells[1].Text;
e.item.Attributes.Add(&quot;ondblclick&quot;, &quot;open(’../ShippedGrid.aspx?id=&quot; + orderItemID + &quot;’)&quot;);
}
复制代码
16.表格超连接列传递参数
<asp:HyperLinkColumn Target=&quot;_blank&quot; headertext=&quot;ID号&quot; DataTextField=&quot;id&quot; NavigateUrl=&quot;aaa.aspx?id=’
<%# DataBinder.Eval(Container.DataItem, &quot;数据字段1&quot;)%>’ &amp; name=’<%# DataBinder.Eval(Container.DataItem, &quot;数据字段2&quot;)%>’ />
复制代码
17.表格点击改变颜色
if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add(&quot;onclick&quot;,&quot;this.style.backgroundColor=’#99cc00’;
this.style.color=’buttontext’;this.style.cursor=’default’;&quot;);
}
复制代码
写在DataGrid的_ItemDataBound里
if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add(&quot;onmouseover&quot;,&quot;this.style.backgroundColor=’#99cc00’;
this.style.color=’buttontext’;this.style.cursor=’default’;&quot;);
e.Item.Attributes.Add(&quot;onmouseout&quot;,&quot;this.style.backgroundColor=’’;this.style.color=’’;&quot;);
}
复制代码
18.关于日期格式   日期格式设定 DataFormatString="{0:yyyy-MM-dd}"   我觉得应该在itembound事件中 e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd")) 19.获取错误信息并到指定页面 不要使用Response.Redirect,而应该使用Server.Transfer   e.g
// in global.asax
protected void Application_Error(Object sender, EventArgs e) {
if (Server.GetLastError() is HttpUnhandledException)
Server.Transfer(&quot;MyErrorPage.aspx&quot;);
复制代码
//其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :) }   Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理 20.清空Cookie
Cookie.Expires=[DateTime];
Response.Cookies(&quot;UserName&quot;).Expires = 0
复制代码
21.自定义异常处理
//自定义异常处理类
using System;
using System.Diagnostics;
namespace MyAppException
{
/// <summary>
/// 从系统异常类ApplicationException继承的应用程序异常处理类。
/// 自动将异常内容记录到Windows NT/2000的应用程序日志
/// </summary>
public class AppException:System.ApplicationException
{
public AppException()
{
if (ApplicationConfiguration.EventLogEnabled)LogEvent(&quot;出现一个未知错误。&quot;);
}
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=&quot;message&quot;>需要记录的文本信息</param>
/// </summary>
public static void WriteError(String message)
{
WriteLog(TraceLevel.Error, message);
}
/// <summary>
/// 将警告信息记录到Win2000/NT事件日志中
/// <param name=&quot;message&quot;>需要记录的文本信息</param>
/// </summary>
public static void WriteWarning(String message)
{
WriteLog(TraceLevel.Warning, message);  
}
/// <summary>
/// 将提示信息记录到Win2000/NT事件日志中
/// <param name=&quot;message&quot;>需要记录的文本信息</param>
/// </summary>
public static void WriteInfo(String message)
{
WriteLog(TraceLevel.Info, message);
}
/// <summary>
/// 将跟踪信息记录到Win2000/NT事件日志中
/// <param name=&quot;message&quot;>需要记录的文本信息</param>
/// </summary>
public static void WriteTrace(String message)
{
WriteLog(TraceLevel.Verbose, message);
}
/// <summary>
/// 格式化记录到事件日志的文本信息格式
/// <param name=&quot;ex&quot;>需要格式化的异常对象</param>
/// <param name=&quot;catchInfo&quot;>异常信息标题字符串.</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(&quot;\r\n&quot;);
}
strBuilder.Append(ex.Message).Append(&quot;\r\n&quot;).Append(ex.StackTrace);
return strBuilder.ToString();
}
/// <summary>
/// 实际事件日志写入方法
/// <param name=&quot;level&quot;>要记录信息的级别(error,warning,info,trace).</param>
/// <param name=&quot;messageText&quot;>要记录的文本.</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(&quot;Application&quot;, ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName );
//写入事件日志
eventLog.WriteEntry(messageText, LogEntryType);
}
catch {} //忽略任何异常
}
} //class ApplicationLog
}
复制代码
22.Panel 横向滚动,纵向自动扩展
<asp:panel style=&quot;overflow-x:scroll;overflow-y:auto;&quot;></asp:panel>
复制代码
23.回车转换成Tab (1)
<script language=&quot;javascript&quot; for=&quot;document&quot; event=&quot;onkeydown&quot;>
if(event.keyCode==13 &amp;&amp; event.srcElement.type!=’button’ &amp;&amp; event.srcElement.type!=’submit’ &amp;&amp;     event.srcElement.type!=’reset’ &amp;&amp; event.srcElement.type!=’’&amp;&amp; event.srcElement.type!=’textarea’);
event.keyCode=9;
</script>
复制代码
(2) //当在有keydown事件的控件上敲回车时,变为tab
public void Tab(System.Web .UI.WebControls .WebControl webcontrol)
{
webcontrol.Attributes .Add (&quot;onkeydown&quot;, &quot;if(event.keyCode==13) event.keyCode=9&quot;);
}
24.DataGrid超级连接列
DataNavigateUrlField=&quot;字段名&quot; DataNavigateUrlFormatString=&quot;http://xx/inc/delete.aspx?ID={0}&quot;
复制代码
25.DataGrid行随鼠标变色
private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType!=ListItemType.Header)
{
e.Item.Attributes.Add( &quot;onmouseout&quot;,&quot;this.style.backgroundColor=\&quot;&quot;+e.Item.Style[&quot;BACKGROUND-COLOR&quot;]+&quot;\&quot;&quot;);
e.Item.Attributes.Add( &quot;onmouseover&quot;,&quot;this.style.backgroundColor=\&quot;&quot;+ &quot;#EFF3F7&quot;+&quot;\&quot;&quot;);
}
}
复制代码
26.模板列
<ASP:TEMPLATECOLUMN visible=&quot;False&quot; sortexpression=&quot;demo&quot; headertext=&quot;ID&quot;>
<ITEMTEMPLATE>
<ASP LABEL text=’<%# DataBinder.Eval(Container.DataItem, &quot;ArticleID&quot;)%>’ runat=&quot;server&quot; width=&quot;80%&quot; id=&quot;lblColumn&quot; />
</ITEMTEMPLATE>
</ASP:TEMPLATECOLUMN>
<ASP:TEMPLATECOLUMN headertext=&quot;选中&quot;>
<HEADERSTYLE wrap=&quot;False&quot; horiz></HEADERSTYLE>
<ITEMTEMPLATE>
<ASP:CHECKBOX id=&quot;chkExport&quot; runat=&quot;server&quot; />
</ITEMTEMPLATE>
<EDITITEMTEMPLATE>
<ASP:CHECKBOX id=&quot;chkExportON&quot; runat=&quot;server&quot; enabled=&quot;true&quot; />
</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(&quot;chkExport&quot;);
chkExport.Checked = true;
}
}
else
{
foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
{
chkExport = (CheckBox)oDataGridItem.FindControl(&quot;chkExport&quot;);
chkExport.Checked = false;
}
}
}
复制代码
27.数字格式化
【<%#Container.DataItem(&quot;price&quot;)%>的结果是500.0000,怎样格式化为500.00?】
<%#Container.DataItem(&quot;price&quot;,&quot;{0:¥#,##0.00}&quot;)%>
int i=123456;
string s=i.ToString(&quot;###,###.00&quot;);
复制代码
28.日期格式化   【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) 29.如何设定全局变量   Global.asax中   Application_Start()事件中   添加Application[属性名] = xxx;   就是你的全局变量 30.怎样作到HyperLinkColumn生成的连接后,点击连接,打开新窗口?   HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank")   【ASPNETMENU】点击菜单项弹出新窗口   在你的menuData.xml文件的菜单项中加入URLTarget="_blank",如:
<?xml version=&quot;1.0&quot; encoding=&quot;GB2312&quot;?>
<MenuData ImagesBaseURL=&quot;images/&quot;>
<MenuGroup>
<MenuItem Label=&quot;内参信息&quot; URL=&quot;Infomation.aspx&quot; >
<MenuGroup ID=&quot;BBC&quot;>
<MenuItem Label=&quot;公告信息&quot; URL=&quot;Infomation.aspx&quot; URLTarget=&quot;_blank&quot; LeftIcon=&quot;file.gif&quot;/>
<MenuItem Label=&quot;编制信息简报&quot; URL=&quot;NewInfo.aspx&quot; LeftIcon=&quot;file.gif&quot; />
复制代码
最好将你的aspnetmenu升级到1.2版 31.读取DataGrid控件TextBox值
foreach(DataGrid dgi in yourDataGrid.Items)
{
TextBox tb = (TextBox)dgi.FindControl(&quot;yourTextBoxId&quot;);
tb.Text....
}
复制代码
33.在DataGrid中有3个模板列包含Textbox分别为 DG_ShuLiang (数量) DG_DanJian(单价) DG_JinE(金额)分别在5.6.7列,要求在录入数量及单价的时候自动算出金额即:数量*单价=金额还要求录入时限制为 数值型.我如何用客户端脚本实现这个功能?
<asp:TemplateColumn HeaderText=&quot;数量&quot;>
<ItemTemplate>
<asp:TextBox id=&quot;ShuLiang&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_ShuLiang&quot;)%>’

/>
<asp:RegularExpressionValidator id=&quot;revS&quot; runat=&quot;server&quot; C ErrorMessage=&quot;must be integer&quot; Validati />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText=&quot;单价&quot;>
<ItemTemplate>
<asp:TextBox id=&quot;DanJian&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_DanJian&quot;)%>’

/>
<asp:RegularExpressionValidator id=&quot;revS2&quot; runat=&quot;server&quot; C ErrorMessage=&quot;must be numeric&quot; Validati />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText=&quot;金额&quot;>
<ItemTemplate>
<asp:TextBox id=&quot;JinE&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_JinE&quot;)%>’ />
</ItemTemplate>
</asp:TemplateColumn><script language=&quot;javascript&quot;>
function DoCal()
{
var e = event.srcElement;
var row = e.parentNode.parentNode;
var txts = row.all.tags(&quot;INPUT&quot;);
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>
复制代码
34.datagrid选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看不到了。 page_load page.smartNavigation=true 35.在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.Attributes.Add(&quot;Width&quot;, &quot;80px&quot;)
}
}
复制代码
36.对话框
private static string ScriptBegin = &quot;<script language=\&quot;JavaScript\&quot;>&quot;;
private static string ScriptEnd = &quot;</script>&quot;;
public static void ConfirmMessageBox(string PageTarget,string Content)
{
string C+Content+&quot;’);&quot;+&quot;if(retValue){window.location=’&quot;+PageTarget+&quot;’;}&quot;;
ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;
Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler;
ParameterPage.RegisterStartupScript(&quot;confirm&quot;,ConfirmContent);
//Response.Write
复制代码
(strScript); } 37. 将时间格式化: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; 38.自定义分页代码:   先定义变量 :
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();
复制代码
39.DataGrid使用:   添加删除确认:
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(&quot;onclick&quot;,&quot;return confirm(’确认删除此项吗?’);&quot;);
}
}
}
复制代码
样式交替:
ListItemType itemType = e.Item.ItemType;
if (itemType == ListItemType.Item )
{
e.Item.Attributes[&quot;onmouseout&quot;] = &quot;javascript:this.style.backgroundColor=’#FFFFFF’;&quot;;
e.Item.Attributes[&quot;onmouseover&quot;] = &quot;javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;&quot; ;
}
else if( itemType == ListItemType.AlternatingItem)
{
e.Item.Attributes[&quot;onmouseout&quot;] = &quot;javascript:this.style.backgroundColor=’#a0d7c4’;&quot;;
e.Item.Attributes[&quot;onmouseover&quot;] = &quot;javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;&quot; ;
}
复制代码
添加一个编号列:
DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable
DataColumn dc=dt.Columns.Add(&quot;number&quot;,System.Type.GetType(&quot;System.String&quot;));
for(int i=0;i<dt.Rows.Count;i++)
{
dt.Rows[&quot;number&quot;]=(i+1).ToString();
}
DataGrid1.DataSource=dt;
DataGrid1.DataBind();
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); //删除函数
}
}
复制代码
40.当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在Web.config,然后在Global.asax中初始化)   在Application_Start中添加以下代码:
Application[&quot;ConnStr&quot;]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.
AppSettings[&quot;ConnStr&quot;].ToString();
复制代码
3 41. 变量.ToString()   字符型转换 转为字符串
12345.ToString(&quot;n&quot;); //生成 12,345.00
12345.ToString(&quot;C&quot;); //生成 ¥12,345.00
12345.ToString(&quot;e&quot;); //生成 1.234500e+004
12345.ToString(&quot;f4&quot;); //生成 12345.0000
12345.ToString(&quot;x&quot;); //生成 3039 (16进制)
12345.ToString(&quot;p&quot;); //生成 1,234,500.00%
复制代码
42、变量.Substring(参数1,参数2);   截取字串的一部分,参数1为左起始位数,参数2为截取几位。 如:string s1 = str.Substring(0,2); 43.在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个FORM,这时可以导向另外一个页面再提交登陆信息)
<SCRIPT language=&quot;javascript&quot;>
<!--
function gook(pws)
{
frm.submit();
}
//-->
</SCRIPT> <body leftMargin=&quot;0&quot; topMargin=&quot;0&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot;>
<form name=&quot;frm&quot; action=&quot; http://www.51aspx.com &quot; method=&quot;post&quot;>
<tr>
<td>
<input id=&quot;f_user&quot; type=&quot;hidden&quot; size=&quot;1&quot; name=&quot;f_user&quot; runat=&quot;server&quot;>
<input id=&quot;f_domain&quot; type=&quot;hidden&quot; size=&quot;1&quot; name=&quot;f_domain&quot; runat=&quot;server&quot;>
<input class=&quot;box&quot; id=&quot;f_pass&quot; type=&quot;hidden&quot; size=&quot;1&quot; name=&quot;pwshow&quot; runat=&quot;server&quot;>
<INPUT id=&quot;lng&quot; type=&quot;hidden&quot; maxLength=&quot;20&quot; size=&quot;1&quot; value=&quot;5&quot; name=&quot;lng&quot;>
<INPUT id=&quot;tem&quot; type=&quot;hidden&quot; size=&quot;1&quot; value=&quot;2&quot; name=&quot;tem&quot;>
</td>
</tr>
</form>
复制代码
文本框的名称必须是你要登陆的网页上的名称,如果源码不行可以用vsniffer 看看。   下面是获取用户输入的登陆信息的代码:
string name;
name=Request.QueryString[&quot;EmailName&quot;];
try
{
int a=name.IndexOf(&quot;@&quot;,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[&quot;Psw&quot;];
}
catch
{
Script.Alert(&quot;错误的邮箱!&quot;);
Server.Transfer(&quot;index.aspx&quot;);
}
复制代码
44.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;
}
}
}
复制代码
45.警告窗口 /**//// <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=&quot;str_Ctl_Name&quot;>获得焦点控件Id值,比如:txt_Name</param>
/// <param name=&quot;str_Message&quot;>提示信息,例子:&quot;请输入您姓名!&quot;</param>
/// <param name=&quot;page&quot;>Page类</param>
public void Alert(string str_Ctl_Name,string str_Message,Page page)
{
page.RegisterStartupScript(&quot;&quot;,&quot;<script>alert('&quot;+str_Message+&quot;');document.forms(0).&quot;+str_Ctl_Name+&quot;.focus(); document.forms(0).&quot;+str_Ctl_Name+&quot;.select();</script>&quot;);
}
复制代码
47.确认对话框
/**//// <summary>
/// 服务器端弹出confirm对话框
/// </summary>
/// <param name=&quot;str_Message&quot;>提示信息,例子:&quot;您是否确认删除!&quot;</param>
/// <param name=&quot;btn&quot;>隐藏Botton按钮Id值,比如:btn_Flow</param>
/// <param name=&quot;page&quot;>Page类</param>
public void Confirm(string str_Message,string btn,Page page)
{
page.RegisterStartupScript(&quot;&quot;,&quot;<script> if (confirm('&quot;+str_Message+&quot;')==true){document.forms(0).&quot;+btn+&quot;.click();}</script>&quot;);
}
复制代码
48.重载确认对话框,点击确定触发一个隐藏按钮事件,点击取消触发一个隐藏按钮事件
/**//// <summary>
/// 服务器端弹出confirm对话框,询问用户准备转向那些操作,包括“确定”和“取消”时的操作
/// </summary>
/// <param name=&quot;str_Message&quot;>提示信息,比如:&quot;成功增加数据,单击\&quot;确定\&quot;按钮填写流程,单击\&quot;取消\&quot;修改数据&quot;</param>
/// <param name=&quot;btn_Redirect_Flow&quot;>&quot;确定&quot;按钮id值</param>
/// <param name=&quot;btn_Redirect_Self&quot;>&quot;取消&quot;按钮id值</param>
/// <param name=&quot;page&quot;>Page类</param>
public void Confirm(string str_Message,string btn_Redirect_Flow,string btn_Redirect_Self,Page page)
{
page.RegisterStartupScript(&quot;&quot;,&quot;<script> if (confirm('&quot;+str_Message+&quot;')==true){document.forms(0).&quot;+btn_Redirect_Flow+&quot;.click();}else{document.forms(0).&quot;+btn_Redirect_Self+&quot;.click();}</script>&quot;);
}
复制代码
49.获得焦点
/**//// <summary>
/// 使控件获得焦点
/// </summary>
/// <param name=&quot;str_Ctl_Name&quot;>获得焦点控件Id值,比如:txt_Name</param>
/// <param name=&quot;page&quot;>Page类</param>
public void GetFocus(string str_Ctl_Name,Page page)
{
page.RegisterStartupScript(&quot;&quot;,&quot;<script>document.forms(0).&quot;+str_Ctl_Name+&quot;.focus(); document.forms(0).&quot;+str_Ctl_Name+&quot;.select();</script>&quot;);
}
复制代码
50.子窗体返回主窗体 /
**////<summary>
///名称:redirect
///功能:子窗体返回主窗体
///参数:url
///返回值:空
///</summary>
public void redirect(string url,Page page)
{
if ( Session[&quot;IfDefault&quot;]!=(object)&quot;Default&quot;)
{
page.RegisterStartupScript(&quot;&quot;,&quot;<script>window.top.document.location.href='&quot;+url+&quot;';</script>&quot;);
}
}
复制代码
51.判断是否为数字
/**//// <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;
}
复制代码

posted on 2012-10-28 12:06 ** 阅读(111) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

公告

你好!

常用链接

留言簿(2)

随笔档案

文章分类

文章档案

新闻档案

相册

收藏夹

C#学习

友情链接

搜索

最新评论

阅读排行榜

评论排行榜