ASP.NET_五大数据控件比较

来源:互联网 发布:文字编辑软件app 编辑:程序博客网 时间:2024/06/05 08:21

数据绑定控件比较 (Reapter/DataList/GridView/DatailsView/FormView):

1.插入功能方面:

DetailsViewFormView具有插入功能,其它控件没有

2.模板

DataList/FormView/Repeater三种必须编辑模板,

GridViewDetailsView只有在将列转换成模板列以后才会出现各种模板.

3.自动分页功能

GridView ,DetailsViewFormView都是2.0版本新增控件,内置了分页,排序等等功能,

其他需要手工定义

4.数据呈现方式:

GridView,DataList,Repeator用于呈现多列数据,

DetailsView,FormView用于呈现单列数据,即常用的数据明细.

 

 

DataListReapter都需要编辑模板列,而在模板列当中可以添加TextBox,同时可以指定TextBoxID从而实现提取用户输入的值,但是DataGridGridView两个件是不需要编辑模板的,它的编辑功能是自动生成的我们无法知道那些文本框的ID,也就无法通过ID来获取用户的输入,那么可以通过对单元格的引用来实现:

private void DataGrid1_UpdateCommand(object source,xx)

{

    string bkid=DataGrid1.DataKeys[e.Item.ItemIndex].toString();//提取主键

    string bktitle=((TextBox)e.Item.Cells[1].Controls[0]).Text;//提取用户的输入

}

 

.进入编辑状态:

DataList1.EditItemIndex = e.Item.ItemIndex;

DataGrid1.EditItemIndex = e.Item.ItemIndex;

GridView1.EditIndex = e.NewEditIndex;

DetailsView1.ChangeMode(DetailsViewMode.Edit);//进入编辑状态

DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);//退出编辑状态

 

 

.设置主键:

DataList1.DataKeyField = "bkid";

DataGrid1.DataKeyField = "bkid";

 

string[] str={"bkid"};

GridView1.DataKeyNames = str;

 

 

.提取主键:

string bkid = DataList1.DataKeys[e.Item.ItemIndex].ToString();//DataList

string bkid = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();//DataGrid

string bkid = GridView1.DataKeys[e.RowIndex].Value.ToString();//GridView

string bkid = DetailsView1.DataKey[0].ToString();

 

.查找控件:

string bktitle = ((TextBox)e.Item.FindControl("txtTile")).Text;//DataList

string bktitle = ((TextBox)e.Item.Cells[1].Controls[0]).Text;//DataGrid

string bktitle = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;

string bktitle = ((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text;

 

 

注意查找控件有两种方法:(各数据绑定控件的都可以用下面两种方法进行查找)

1.如果知道控件的ID可以用这种方法

((TextBox)e.Item.FindControl("txtTile")).Text;//这是查找

2.如果不知道控件的ID可用这种方法

((TextBox)e.Item.Cells[1].Controls[0]).Text;//这是索引

 

 

.给删除按钮添加确认:

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)

     {

         if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

         {

             LinkButton lbtn =(LinkButton) e.Item.FindControl("lbtndelete");

             lbtn.Attributes.Add("OnClick","return confirm(‘确定要删除吗?)");

         }

     }

 

protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)

     {

         if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)

         {

             LinkButton lbtn = (LinkButton)e.Item.Cells[3].Controls[0];

             lbtn.Attributes.Add("OnClick","return confirm(‘确认删除?‘)");

         }

     }

 

 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

     {

         if(e.Row.RowType== DataControlRowType.DataRow)

         {

             string strid = e.Row.Cells[0].Text;//获取第一行的字段值;

             e.Row.Cells[3].Attributes.Add("OnClick", "return confirm(‘确认删除/""+strid+"/"?‘)");

             //用了两个转义符将第一列的值用引号括起来,注意转义符后面一个将不被解释,是直接放上去;

 

         }

     }

 

ASP.NET 程序中常用的三十三种代码(1)

     1. 打开新的窗口并传送参数:  
传送参数:
response.write("
scriptwindow.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 + "’");
<>

ASP.NET 程序中常用的三十三种代码(2) }
  双击表格打开新一页

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

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会导致postback的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理
  10.清空Cookie
<>

ASP.NET 程序中常用的三十三种代码(3)
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);  
<>

ASP.NET 程序中常用的三十三种代码(4)    }
   /// 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;

ASP.NET 程序中常用的三十三种代码(5)        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"
  14.DataGrid超级连接列
ataNavigateUrlField="字段名" 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.NET 程序中常用的三十三种代码(6) /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))([AMPMampm]{2,2})))?$
<>

ASP.NET 程序中常用的三十三种代码(7)   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.读取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="单价"
<>

ASP.NET 程序中常用的三十三种代码(8) 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;ie.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;

ASP.NET 程序中常用的三十三种代码(9)
 
Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler;
 
ParameterPage.RegisterStartupScript("confirm",ConfirmContent);
 
//Response.Write(strScript);
}

    27. 将时间格式化:string aa=DateTime.Now.ToString("yyyyMMdd");
  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)  f(di.ItemType==ListItemType.Itemdi.ItemType==ListItemType.AlternatingItem)   {    ((LinkButton)di.Cells[8].Controls[0]).Attributes.Add("onclick","return confirm(’确认删除此项吗?’);");
  }
 }
}
  样式交替:
ListItemType itemType = e.Item.ItemType;

ASP.NET 程序中常用的三十三种代码(10) 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’;" ;
}
  添加一个编号列:

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

ASP.NET 程序中常用的三十三种代码(11) 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);
  33.在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个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");

 

数据绑定(Databind)与 repeater 控件的使用。

repeater 控件 用来循环输出

摸板介绍:

 <ItemTemplate> 
正常项目显示模板  1 3 5 7 行显示 </ItemTemplate>

<AlternatingItemTemplate>
交错项显示模板 2 4 6 8 行显示</AlternatingItemTemplate>

<SeparatorTemplate>
每行分隔项模板</SeparatorTemplate>

 <HeaderTemplate>
页眉</HeaderTemplate>

<FooterTemplate>
页脚</FooterTemplate>

数据绑定中 Container的使用

<%# ((DataRowView)Container.DataItem)["num"] %> 或者
<%# DataBinder.Eval(Container.DataItem,"num","{0}") %>    
效果同asp<%%=rs("num")>

从容器中取出 num  
<%# DataBinder.Eval(Container.DataItem,"num","{0
c}") %>  {}中既是要生成的数据 c表示输入人民币符号。
如下例:

数据库对象的建立
            con.Open();
            SqlDataAdapter sad = new SqlDataAdapter();//
建立数据适配器对象
            sad.SelectCommand= new SqlCommand("select * from person",con);//
实例化
            DataSet ds = new DataSet();//
定义数据集
            sad.Fill(ds, "info");//
使用数据适配器填充数据集 填充到info 表中
            this.Repeater1.DataSource = ds.Tables["info"];//
设置数据源
            this.Repeater1.DataBind();//
绑定

   <asp:Repeater ID="Repeater1" runat="server" >
     <ItemTemplate>
     <%# DataBinder.Eval(Container.DataItem,"pname","
姓名:{0}") %>
       <%# DataBinder.Eval(Container.DataItem,"psex") %>
     </ItemTemplate>
     <AlternatingItemTemplate>
     <font color=blue>
     <%# DataBinder.Eval(Container.DataItem,"pname","
姓名:{0}") %>
       <%# DataBinder.Eval(Container.DataItem,"psex") %></font>
     </AlternatingItemTemplate>
    
     <HeaderTemplate>
页眉
     </HeaderTemplate>
     <FooterTemplate>
页脚
     </FooterTemplate>
     <SeparatorTemplate>
    
     <hr color=blue size=1 />
     </SeparatorTemplate>
        </asp:Repeater>

分页的设计:
       int curpage =    1 ; 
     PagedDataSource ps = new PagedDataSource();
        ps.DataSource = ds.Tables["info"].DefaultView;
        ps.AllowPaging = true;
        ps.PageSize = 4;
        ps.CurrentPageIndex = curpage - 1;
        this.Repeater1.DataSource = ps;//
设置数据源
        this.Repeater1.DataBind();//
绑定
每次点击时改变“curpage” 的值即可。
下一页 curpage  加一就可以了

 在表格中显示的实现:
1、在页眉和页脚中分别加入<table></table>
 <HeaderTemplate> <table>   </HeaderTemplate>

<FooterTemplate></table> </FooterTemplate>

2
、在   </ItemTemplate><tr><td><%#  %></td><tr>  <AlternatingItemTemplate>

 

 

数据连接之--Datalist 的使用(查看、编辑、删除)

<数据库绑定:
       
        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = new SqlCommand("select * from person", con);
        DataSet ds = new DataSet();
        sda.Fill(ds, "person");
        this.DataList1.DataKeyField = "pid";
        this.DataList1.DataSource = ds.Tables["person"];
        this.DataList1.DataBind();

<> Datalist属性生成器
编辑 更新,删除,取消 CommandName分别是edit  update delete cancel ,这样在datalist的事件中就可以直接响应这些事件,以便进行操作。

样式有列表如下:
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand" OnEditCommand="DataList1_EditCommand" OnCancelCommand="DataList1_CancelCommand" OnUpdateCommand="DataList1_UpdateCommand">
        <ItemTemplate>
            <asp:LinkButton ID="LinkButton1" runat="server" CommandName="select">
查看详细信息</asp:LinkButton>
            <asp:LinkButton ID="LinkButton2" runat="server" CommandName="edit" OnClick="LinkButton2_Click">
编辑</asp:LinkButton>
            <asp:LinkButton ID="LinkButton5" runat="server" CommandName="delete">
删除</asp:LinkButton><%# DataBinder.Eval(Container.DataItem ,"pname") %><%# DataBinder.Eval(Container.DataItem ,"psex") %>

        </ItemTemplate>
        <SelectedItemTemplate>
        <%# DataBinder.Eval(Container.DataItem,"pid","
序列号:{0}") %><br>
           <%# DataBinder.Eval(Container.DataItem,"pname") %>
              <%# DataBinder.Eval(Container.DataItem,"psex") %>
        </SelectedItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="LinkButton3" runat="server" CommandName="cancel">
取消</asp:LinkButton>
                <asp:LinkButton ID="LinkButton4" runat="server" CommandName="update">
保存</asp:LinkButton>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%#
DataBinder.Eval(Container.DataItem ,"pname") %>'></asp:TextBox>
            </EditItemTemplate>
            <AlternatingItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False"
                Font-Strikeout="False" Font-Underline="False" ForeColor="Maroon" />
            <ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False"
                Font-Underline="False" ForeColor="Green" />
        </asp:DataList>

程序代码:

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "select")
        {
            this.DataList1.SelectedIndex = e.Item.ItemIndex;//
选择
            this.DataList1.DataBind();
        }
    }
    protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
    {
        this.DataList1.EditItemIndex = e.Item.ItemIndex;//
编辑
        this.DataList1.DataBind();
    }

    protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
    {
        this.DataList1.EditItemIndex = -1;//
取消
        this.DataList1.DataBind();
    }
    protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)//
更新
    {
        string pid=this.DataList1.DataKeys[e.Item.ItemIndex].ToString();
        string name = ((TextBox)e.Item.FindControl("TextBox1")).Text;
        SqlConnection con = connecttion.ado.sqldb();
        con.Open();
        SqlCommand cmd = new SqlCommand("update person set pname='"+name+ "'where pid='" + pid + "'",con);
        cmd.ExecuteNonQuery();
        this.DataList1.EditItemIndex = -1;
        this.DataList1.DataBind();
        Response.Write(pid+name);
    }
}

Datagrid 控件的使用

分页


protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        this.DataGrid1.CurrentPageIndex = e.NewPageIndex;
        this.datagridview();
    }

隐藏列

 this.DataGrid1.Columns[2].Visible = false;//
隐藏第三列(只是表面上的隐藏)
  this.datagridview();

鼠标经过每行时高亮显示:

  protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            e.Item.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");
            e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=c");
        }
    }

双向排序:

DataGrid1
SortCommand 事件激活排序事件
 
protected void DataGrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
    {
        if (ViewState["order"] == null)
        {
            ViewState["order"] = "ASC";//viewstate[""]
session[""] 差不多,储存在客户端
        }
        else
        {
            if (ViewState["order"].Tostring() == "ASC")
            {
                ViewState["order"] = "DESC";
            }
            else
            {
                ViewState["order"] = "ASC";
            }
       
        }
        SqlConnection con = connecttion.ado.sqldb();
        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = new SqlCommand("select * from person", con);
        DataSet ds = new DataSet();
        sda.Fill(ds, "person");
        ds.Tables["person"].DefaultView.Sort = e.SortExpression + " " + ViewState["order"].ToString();
        //
默认视图的Sort属性就是排序属性 e.SortExpression 就是属性生成器中排序表达式的字段
        this.DataGrid1.DataSource = ds.Tables["person"].DefaultView;//
        this.DataGrid1.DataBind();
    }

绑定查看详细信息列




show.aspx中用 string id = Request.QueryString["id"] 接收。

datagrid DataKeyfield="id"  按照索引取的,使用时可以取得当前行的id 

当要删除或者修改每一行时通过  this.DataGrid1.DataKeys[e.Item.ItemIndex]来获得当前行的i


datagrid删除的实现

首先在属性生成器中添加删除按钮,然后在dadagridDeleteCommand 事件中编写代码即可

protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
    {
        string id = this.DataGrid1.DataKeyField[e.Item.ItemIndex];
        SqlConnection con = connecttion.ado.sqldb();
        con.Open();
        SqlCommand cmd=new SqlCommand("delete from person where pid='"+id+"'",con)

        cmd.ExecuteNonQuery();
        this.datagridview();
    }

如果要在删除时显示确认后 再删除功能
DataGrid1_ItemDataBound的事件中 加第三行就可以了
 
protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)//
普通行和交错行的事件
        {
            e.Item.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");//
鼠标在的时候
            e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=c");//
鼠标离开的时候
            ((LinkButton)(e.Item.Cells[4].Controls[0])).Attributes.Add("onclick", "return confirm('
确认删除吗?')");//点任一行的第5列时触发的事件
        }
    }


Datagrid
的编辑功能:

更新:
       string id = this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
取的更新行的id
        string pname = ((TextBox)(e.Item.Cells[1].Controls[0])).Text; 
取的本行第二个字段文本框的值
        string psex = ((TextBox)(e.Item.Cells[2].Controls[0])).Text;

下面加入数据库就可以了,

在更新时可使用验证控件进行验证,首先把那一列在属性生成器中 转换成模板列,然后在模板中添加验证控件就可以了。

 

ASP.NET 2.0 FormView控件控制显示(1)

  ASP.NET 2.0FormView控件类似于DetailsView控件,因为它能方便地显示后端数据源的单个记录。本文将讨论这个控件的语法和应用。

  用户化

  虽然这两个控件一次显示一条记录,DetailsViewFormView的关键差别在于:FormView利用用户定义的模板;DetailsView则使用行字段。FormView控件没有预先定义数据布局;相反,你建立一个包含控件的模板来显示记录中的单个字段。模板中包含建立表单所要用到的格式、控件和绑定表达式。

  你可以控制数据记录以三种形式显示:编辑、查看和添加一条新记录。另外,你可以包括和格式化标题与页脚元素。你还可以利用FormView控件各个部分中的任何一个有效的ASP.NET控件。

  语法

  宣称和使用一个FormView控件实例与宣称和使用一个DetailsView控件实例非常相似。它们的主要区别是,因为没有默认设置可以使用,你必须在FormView控件中包含显示数据的格式和模板。列表A显示了打开FormView元素标签的一部分语法。

  你可能已经注意到,许多属性和HTML表格元素相对应,如标题和边框。这说明ASP.NET使用HTML表格来呈现FormView控件。

  你可以通过微软网站在线查看一个更加全面的FormView控件属性列表。下表列出了一些值得关注的重要属性。

  ·AllowPaging:一个说明用户能否对指定数据源中的记录分页的布尔值。如果设为真,则在所显示记录的底部显示默认的分页数字系统(1到记录的数量)。分页链接可以通过各种分页属性自定义。

  ·DataKeyNames:数据源的键字段。

  ·DataSourceID:用来移植FormView控件数据源元素ID。如果使用SQL Server,它与分配给SqlDataSource元素的ID对应。

  ·DefaultMode:允许你指定控件的默认行为。也就是说,在用户访问时,它最初如何显示。可能的值包括:ReadOnlyInsertEdit

  ·EmptyDataText:遇到空数据值时显示的文本。

  宣称FormView控件时,还必须对它的内容进行相应格式化。它的数据通过模板显示。FormView控件主要使用五个模板:

  ·ItemTemplate:它控制用户查看数据时的显示情况。

  ·EditItemTemplate:它决定用户编辑记录时的格式和数据元素的显示情况。在这个模板内,你将使用其它控件,如TextBox元素,允许用户编辑值。

  ·InsertItemTemplate:与编辑一条记录相似,这个模板控制允许用户在后端数据源中添加一条新记录的字段的显示。由于输入了新的值,应该根据数据的要求允许用户自由输入文本或限制某些值。

  ·FooterTemplate:决定FormView控件表格页脚部分显示的内容,如果有的话。

  ·HeaderTemplate:决定FormView控件表格标题部分显示的内容,如果有的话。

  这些模板允许你控制绑定到一个FormView控件的数据的显示和行为。例如,列表B中的ASP.NET Web表单连接到标准的Northwind数据库,允许用户通过名字、姓、雇用日期和家庭电话号码字段查看、编辑、删除和添加新的员工记录。

  它使用TextField控件显示被编辑或添加的数据,以及只是为了查阅而显示的值。ItemTemplate使用CSS技巧">CSS格式化表格,而InsertTemplate则使用HTML样式进行格式化,到底使用哪种方法由开发者决定。

  注:ASP.NETButton控件添加、编辑、删除和保存记录。

  在Button控件中,NewCommandName值将记录转换为插入模式并加载InsertItemTemplate模板,它允许用户输入一个新记录值。你可以用EditCommandName值给ItemTemplate增加一个新按钮,使FormView控件进入编辑模式。

  可以给ItemTemplate模板增加一个带DeleteCommnadName值的按钮,允许用户从数据源中删除当前记录。UpdateCommnadName保存数据,而Cancel终止操作。

  开发者控制

  许多ASP.NET 2.0新功能的易用性令人惊喜。FormViewDetailsView的简单功能进行了扩张,允许你根据需要轻松控制要格式化的显示内容。这个新控件为你交付解决方案提供另一个选项。

 

 

原创粉丝点击