ASP.NET 2.0 绑定高级技巧


1.简单数据绑定定

<!-- ASP.NET 1.x data binding expression  -->
<% # DataBinder.Eval(Container.DataItem, "Price" %>
<!-- Equivalent ASP.NET 2.0 data binding expression  -->
<% Eval("Price" %>
<!-- XML data binding  -->
<% # XPath("Price" %>
2.数据源控件
控件名                                     控件描述
SqlDataSource                       一切支持SQL语句的数据源控件
AccessDataSource               Access数据源控件
XmlDataSource                     XML数据源控件
ObjectDataSource                自行编写组件的数据源控件
SiteMapDataSource             页面导航控件的数据源控件
 2.1 SqlDataSource关键属性
名称                                               描述
ConnectionString                        连接数据库的连接字符串
SelectCommand                           用于执行查询的命令
InsertCommand                           用于执行插入的命令
UpdateCommand                        用于执行更新的命令
DeleteCommand                          用于执行删除的命令
DataSourceMode                        指定数据源类型是DataSet 或DataReader( 默认值
=  DataSet)
ProviderName                              指定供应商(默认值
=  SQL Server .NET provider)
 2.2 SqlDataSource 支持通过以下属性进行数据缓存
属性名                                         描述
EnableCaching                           指定是否打开缓存(默认值
=   false )
CacheDuration                           指定结果被缓存多少妙
CacheExpirationPolicy              指定缓存间隔是sliding 还是absolute
CacheKeyDependency             使缓存依赖于一个特定键值
SqlCacheDependency               使缓存依赖于一个特定数据库实体
2.3 参数化命令  XxxParameter 类型指定参数来源
名称                                      描述
SelectParameters                为查询命令指定参数
InsertParameters                为插入命令指定参数
UpdateParameters              为更新命令指定参数
DeleteParameters               为删除命令指定参数
FilterParameters                 为过滤器命令指定参数
2.4 XxxParameter 类型
名称                                               描述
ControlParameter                         指定一个源自于控件的参数
CookieParameter                          指定一个源自于cookie的参数
FormParameter                             指定一个源自于表单的参数
ProfileParameter                           指定一个源自于profile的参数
QueryStringParameter                 制定于一个来源于查询字符串的参数
Parameter                                      为数据源绑定一个参数
SessionParameter                        指定一个源自于session的参数
2.5 使用ControlParameter例子
< asp:SqlDataSourceID ="Countries"  RunAt ="server"
ConnectionString
="server=localhost;database=northwind;"
SelectCommand
="select distinct country from customers order by country"   />
< asp:SqlDataSourceID ="Customers"  RunAt ="server"
ConnectionString
="server=localhost;database=northwind;"
SelectCommand
="select * from customers where country =@Country" >
< SelectParameters >
< asp:ControlParameterName ="Country"  ControlID ="MyDropDownList"
PropertyName
="SelectedValue"   />
</ SelectParameters >
</ asp:SqlDataSource >
< asp:DropDownListID =" MyDropDownList"  DataSourceID ="Countries"
DataTextField
="country"  AutoPostBack ="true"  RunAt ="server"   />
< asp:DataGridDataSourceID ="Customers"  RunAt ="server"   />
2.7 调研存储过程例子
< asp:SqlDataSourceID ="Countries"  RunAt ="server"
ConnectionString
="server=localhost;database=northwind;"
SelectCommand
="proc_GetCountries"   />
< asp:SqlDataSourceID ="Customers"  RunAt ="server"
ConnectionString
="server=localhost;database=northwind;"
SelectCommand
="proc_GetCustomers" >
< SelectParameters >
< asp:ControlParameterName ="Country"  ControlID ="MyDropDownList"
PropertyName
="SelectedValue"   />
</ SelectParameters >
</ asp:SqlDataSource >
< asp:DropDownListID ="MyDropDownList"  DataSourceID ="Countries"
DataTextField
="country"  AutoPostBack ="true"  RunAt ="server"   />
< asp:DataGridDataSourceID ="Customers"  RunAt ="server"   />
CREATE PROCEDURE proc_GetCustomers
@Country nvarchar(32) AS
SELECT * FROM Customers
WHERE Country = @Country
GO
CREATE PROCEDURE proc_GetCustomers
CREATE PROCEDURE proc_GetCountriesAS
SELECT DISTINCT Country
FROM Customers
ORDER BY Country
GO
3.XmlDataSource 使用XML 作为数据源
支持缓存与XSL 转换,只支持查询绑定,不支持更新
< asp:XmlDataSourceID ="Rates"  DataFile ="Rates.xml"  RunAt ="server"   />
< asp:TreeViewID ="MyTreeView"  DataSourceID ="Rates"  RunAt ="server"   />
3.1 XmlDataSource的关键属性
名称                                                    描述
DataFile XML                                    数据文件的路径
TransformFile                                    含有XSL 风格定义的数据文件路径
EnableCaching                                  指定是否开启cache (默认值= false)
XPath XPath                                      表达式用来确认数据
CacheDuration                                  以秒为单位的时间间隔
CacheExpirationPolicy                     指定时间间隔是sliding 还是absolute
CacheKeyDependency                    创建缓存依存于某个键
4. ObjectDataSource
从数据组件绑定数据,提供中间件的数据绑定,使数据访问和UI脱离,两种数据绑定方式
SelectMethod, InsertMethod, UpdateMethod,and DeleteMethod
可选择是否使用缓存,可选择是否使用参数
4.1 ODS 关键属性
ODS 关键属性
名称                                                         描述
InsertParameters                                    指定插入方法参数
UpdateParameters                                 指定更新方法参数
DeleteParameters                                   指定删除方法参数
SelectParameters                                    指定查询方法参数
CacheDuration                                       缓存间隔时间以秒为单位
SqlCacheDependency                          基于某个数据实体的缓存
创建和清除
ObjectDataSource.SelectMethod 可以使用静态方法也可以使用一个类的新实例
如果使用实例方法:ODS 在每次调用的时候创建一个新实例类必须具有公共的建构函数
使用ObjectCreated 和ObjectDisposing 元素可以初始化和撤销函数
5.增强的DataGrid 控件
支持复杂的数据单元格类型,包括CheckBoxFields在<Columns> 元素中声明高可定制的用户界面
gridView 列类型:
名称                                             描述
BoundField                                 显示数据库中取出的文本
ButtonField                                显示按钮
CheckBoxField                           使用check boxes显示一个boolean型变量
HyperLinkField                          显示一个超链接
TemplateField                            显示一个自定义的HTML模板
CommandField                          显示一个查询或者编辑按钮
ImageField                                 显示一个图片
6. 冲突判定
先入胜利
如果数据在取出之后被改变,则修改失败
UpdateCommand结构构成指定ConflictDetection
= “CompareAllValues”来实现
后入胜利
无论数据是否被修改,该修改都会成功
UpdateCommand结构构成指定ConflictDetection
= “OverwriteChanges”来实现
6.1 先入胜利法则更新
< asp:SqlDataSourceID ="Employees"  RunAt ="server"
ConnectionString
="server=localhost;database=northwind;"
SelectCommand
="select employeeid, lastname, firstnamefrom employees"
UpdateCommand
="update employees set lastname=@lastname, firstname=
@firstnamewhere employeeid=@original_employeeid and lastname=
@original_lastnameand firstname=@original_firstname"

ConflictDetection
="CompareAllValues" >
< UpdateParameters >
< asp:ParameterName ="EmployeeID"  Type ="Int32"   />
< asp:ParameterName ="lastname"  Type ="String"   />
< asp:ParameterName ="firstname"  Type ="String"   />
</ UpdateParameters >
</ asp:SqlDataSource >
< asp:GridViewDataSourceID ="Employees"  Width ="100%"  RunAt ="server"
DataKeyNames
="EmployeeID"  AutoGenerateEditButton ="true"   />
7.错误检测
数据更新后控件调用的事件GridView.RowUpdated,DetailsView.ItemUpdated,SqlDataSource.Updated, etc.
处理“status”的事件,无论数据库是否异常允许数据库异常被处理或者再次抛弃,显示多少数据库行被修改
处理更新错误
< asp:SqlDataSourceID ="Employees"  RunAt ="server"  
UpdateCommand
=""  OnUpdated ="OnUpdateComplete" >

</ asp:SqlDataSource >

void OnUpdateComplete (Object source, SqlDataSourceStatusEventsArgse)
{
if (e.Exception!= null) {
// Exception thrown. Set e.ExceptionHandledto true to prevent
// the SqlDataSourcefrom throwing an exception, or leave it set
// to false to allow SqlDataSourceto rethrowthe exception
}
else if (e.AffectedRows== 0) {
// No exception was thrown, but no records were updated,either.
// Might want to let the user know that the update failed
}
}


2005年11月29日

1.为按钮添加确认对话框

Button1.Attributes.Add("onclick","return confirm(’确认?’)");
button.attributes.add("onclick","if(confirm(’are you sure...?’)){return true;}else{return false;}")

2.删除表格选定记录

//获得DataGrid主键
int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex];
string deleteCmd = "DELETE from Employee where emp_id = " + intEmpID.ToString();

3.删除表格记录警告

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;
 }
}

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

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 + "’);");
}

5.双击表格连接到另一页

在itemDataBound事件中

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 + "’");
}

6.双击表格打开新一页

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 + "’)");
}

7.表格超连接列传递参数

<asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" NavigateUrl="aaa.aspx?id=’
 <%# DataBinder.Eval(Container.DataItem, "数据字段1")%>’&name=’<%# DataBinder.Eval(Container.DataItem, "数据字段2")%>’/>

8.表格点击改变颜色

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’;");
}

9.在表格行中移动鼠标时改变颜色

写在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=’’;");
}

10.关于日期格式

日期格式设定

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

我觉得应该在itembound事件中

e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))

11.获取错误信息并到指定页面

不要使用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的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理。

12.清空Cookie

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

13.自定义异常处理

//自定义异常处理类
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.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 );
     //写入事件日志
     eventLog.WriteEntry(messageText, LogEntryType);

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

14.Panel 横向滚动,纵向自动扩展

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

15.回车转换成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>

οnkeydοwn="if(event.keyCode==13) event.keyCode=9"

16.DataGrid超级连接列

DataNavigateUrlField="字段名" DataNavigateUrlFormatString=http://xx/inc/delete.aspx?ID={0}

17.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"+"/"");
 }
}

18.模板列

<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;
  }
 }
}

19.数字格式化

【<%#Container.DataItem("price")%>的结果是500.0000,怎样格式化为500.00?】

<%#Container.DataItem("price","{0:¥#,##0.00}")%>

int i=123456;
string s=i.ToString("###,###.00");

20.日期格式化

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

21.怎样作到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版

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")%>’
οnkeyup=" 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")%>’
οnkeyup=" 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添加删除确认:

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

30.DataGrid样式交替:

ListItemType itemType = e.Item.ItemType;

if (itemType == ListItemType.Item )
{
 e.Item.Attributes["onmouseout"] = " this.style.backgroundColor=’#FFFFFF’;";
 e.Item.Attributes["onmouseover"] = " this.style.backgroundColor=’#d9ece1’;cursor=’hand’;" ;
}
else if( itemType == ListItemType.AlternatingItem)
{
 e.Item.Attributes["onmouseout"] = " this.style.backgroundColor=’#a0d7c4’;";
 e.Item.Attributes["onmouseover"] = " this.style.backgroundColor=’#d9ece1’;cursor=’hand’;" ;
}

31.DataGrid添添加一个编号列:

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

32.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;
 }
}

33.DataGrid添将当前页面中DataGrid1显示的数据全部删除

foreach(DataGridItem thisitem in DataGrid1.Items)
{
 if(((CheckBox)thisitem.Cells[0].Controls[1]).Checked)
 {
  string strloginid= DataGrid1.DataKeys[thisitem.ItemIndex].ToString();
  Del (strloginid); //删除函数
 }
}

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

在Application_Start中添加以下代码:

Application["ConnStr"]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.
   AppSettings["ConnStr"].ToString();

35.变量.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%

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

<SCRIPT language="javascript">
<!--
 function gook(pws)
 {
  frm.submit();
 }
//-->

</SCRIPT> <body leftMargin="0" topMargin="0" οnlοad=" 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");
}





    摘要:代码    (全文共11475字)——点击 此处阅读全文


2005年11月24日

1. asp.net 2.0中的MaxPageStateFieldLength 属性 
  在asp.net 2.0中,可以强制对viewstate进行分段传输了,使用的是Page.MaxPageStateFieldLength 属性,可以设置viewstate中,每个页面状态字段的最大字节数。格式如下,要在WEB.CONFIG文件里设置的:
    < pages maxPageStateFieldLength="5" />
    其中,将设置把viewstate为不超过5字节,如果实际的viewstate超过该值,将进行分段传输,但每个分段的大小依然不超过 maxPageStateFieldLength中的设置值, 默认设置值为-1,表示不对其进行分段传输。
2.Click button only once in asp.net 2.0
protected void Page_Load(object sender, EventArgs e)
 2     {
 3         PostBackOptions options = new PostBackOptions(Button1,string.Empty);
 4 
 5         StringBuilder sb = new StringBuilder();
 6         if (Button1.CausesValidation && this.GetValidators(Button1.ValidationGroup).Count > 0)
 7         {
 8             options.ClientSubmit = true;
 9             options.PerformValidation = true;
10             options.ValidationGroup = Button1.ValidationGroup;
11 
12             sb.Append("if (typeof(Page_ClientValidate) == 'function')");
13             sb.Append("if(Page_ClientValidate(/"" + Button1.ValidationGroup + "/")==false) return false;");
14         }
15         if (!string.IsNullOrEmpty(Button1.PostBackUrl))
16             options.ActionUrl = HttpUtility.UrlPathEncode(Button1.ResolveClientUrl(Button1.PostBackUrl));
17         
18         sb.Append("this.disabled = true;");
19         sb.Append(ClientScript.GetPostBackEventReference(options));
20         sb.Append(";");
21         Button1.Attributes.Add("onclick", sb.ToString());
22     }
3.asp.net 2.0中得到sqldatasource返回的行数
在asp.net 2.0中,gridview是和sqldatasource控件绑定的,那么如何得到sqldatasource返回的记录的行数呢?比如sqldatasource控件中用select * from ....,如何返回其记录行数?在.net 2.0中,可以通过sqldatasource的OnSelected事件实现,并且对select事件SqlDataSourceStatusEventArgs参数中的AffectedRows属性设置一下就可以了,具体核心代码如下:
 protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
 {
   totalRows.Text = e.AffectedRows.ToString();
 }
  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;user id=sa;password=123456;"  ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName] FROM [Customers]" OnSelected="SqlDataSource1_Selected"></asp:SqlDataSource>

4.在asp.net 1.1中,当要在page_load页面中,设置某个控件为默认的焦点按钮(也就是默认焦点是在这个控件上的),可能要用到javascript的代码,而在ASP.NET 2.0中,不用这些麻烦了,在form代码中,使用
  defaultbutton  defaultfocus属性就可以了,比如
 <form id="Form1"

    defaultbutton="BtnSubmit"

    defaultfocus="TextBox1"

    runat="server">
则在页面加载时,默认的button按钮时btnsubmit,焦点默认就在texbox1上了

5.asp.net 2.0中的弹出对话框

在asp.net 1.1中,要做1个弹出的对话框的话,一般是在服务端的代码中这样写:

btnClick.Attributes.Add("onclick", "return confirm('Are you sure?');");

现在在ASP.NET 2.0中,只要使用客户端的代码就可以拉,新多了个onclientclick,这样写
<asp:button id="btnClick" runat="server" OnClientClick="return confirm('Are you sure?');" text="Button"></asp:button>
5.自定义的页面控件,
比如在ASP。NET 1。1中,要声明自定义的页面控件,
通常要在用到的每页都要加入register prefix=........这样的,很麻烦,而在asp.net 2.0中,如果你确定一个页面自定义控件要在
整个项目中用到,只需要在WEB.CONFIG中加入
<system.web>
    <pages>

    <controls>

      <add tagPrefix="prefixname" namespace="namespacename "/>

    </controls>

   </pages>

</system.web>
其中prefixname为控件的标识,namespace为命名空间就可以了。

    <controls>

      <add tagPrefix="prefixname" namespace="namespacename "/>

    </controls>

   </pages>

</system.web>
其中prefixname为控件的标识,namespace为命名空间就可以了。

    <controls>

      <add tagPrefix="prefixname" namespace="namespacename "/>

    </controls>

   </pages>

</system.web>
其中prefixname为控件的标识,namespace为命名空间就可以了。

    <controls>

      <add tagPrefix="prefixname" namespace="namespacename "/>

    </controls>

   </pages>

</system.web>
其中prefixname为控件的标识,namespace为命名空间就可以了。




http://ghd258.cnblogs.com/archive/2005/11/22/282367.html




    摘要:http://ghd258.cnblogs.com/archive/2005/11/23/283136.html    (全文共97178字)——点击 此处阅读全文


2005年04月20日


    摘要:触发器    (全文共28098字)——点击 此处阅读全文


2005年04月12日


    摘要:.NET Remoting中的事件处理     (全文共54546字)——点击 此处阅读全文


2005年03月30日


    摘要:在Web编程中,我们常需要把一些本地文件上传到Web服务器上,上传后,用户可以通过浏览器方便地浏览这些文件,应用十分广泛。    (全文共3777字)——点击 此处阅读全文


2005年03月16日


    摘要:是本人在网上收集的自动更新资料,经过研究实现的其中的功能    (全文共180665字)——点击 此处阅读全文

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值