ASPNET五大数据控件.docx
《ASPNET五大数据控件.docx》由会员分享,可在线阅读,更多相关《ASPNET五大数据控件.docx(33页珍藏版)》请在冰豆网上搜索。
![ASPNET五大数据控件.docx](https://file1.bdocx.com/fileroot1/2023-1/3/62f7902d-e4d5-477a-b55f-8b88ab582098/62f7902d-e4d5-477a-b55f-8b88ab5820981.gif)
ASPNET五大数据控件
数据绑定控件比较(Reapter\DataList\GridView\DatailsView\FormView):
1.插入功能方面:
DetailsView和FormView具有插入功能,其它控件没有
2.模板
DataList\FormView\Repeater三种必须编辑模板,而
GridView和DetailsView只有在将列转换成模板列以后才会出现各种模板.
3.自动分页功能
GridView,DetailsView和FormView都是2.0版本新增控件,内置了分页,排序等等功能其他需要手工定义
4.数据呈现方式:
GridView,DataList,Repeator用于呈现多列数据,DetailsView,FormView用于呈现单列数据,即常用的数据明细.
DataList和Reapter都需要编辑模板列,而在模板列当中可以添加TextBox,同时可以指定TextBox的ID从而实现提取用户输入的值,但是DataGrid和GridView两个件是不需要编辑模板的,它的编辑功能是自动生成的我们无法知道那些文本框的ID,也就无法通过ID来获取用户的输入,那么可以通过对单元格的引用来实现:
privatevoidDataGrid1_UpdateCommand(objectsource,xx)
{
stringbkid=DataGrid1.DataKeys[e.Item.ItemIndex].toString();//提取主键
stringbktitle=((TextBox)e.Item.Cells[1].Controls[0]).Text;//提取用户的输入
}
1.进入编辑状态:
DataList1.EditItemIndex=e.Item.ItemIndex;
DataGrid1.EditItemIndex=e.Item.ItemIndex;
GridView1.EditIndex=e.NewEditIndex;
DetailsView1.ChangeMode(DetailsViewMode.Edit);//进入编辑状态DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);//退出编辑状态
2.设置主键:
DataList1.DataKeyField="bkid";
DataGrid1.DataKeyField="bkid";
string[]str={"bkid"};
GridView1.DataKeyNames=str;
3.提取主键:
stringbkid=DataList1.DataKeys[e.Item.ItemIndex].ToString();//DataList
stringbkid=DataGrid1.DataKeys[e.Item.ItemIndex].ToString();//DataGrid
stringbkid=GridView1.DataKeys[e.RowIndex].Value.ToString();//GridView
stringbkid=DetailsView1.DataKey[0].ToString();
4.查找控件:
stringbktitle=((TextBox)e.Item.FindControl("txtTile")).Text;//DataList
stringbktitle=((TextBox)e.Item.Cells[1].Controls[0]).Text;//DataGrid
stringbktitle=((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
stringbktitle=((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;//这是索引
5.给删除按钮添加确认:
protectedvoidDataList1_ItemDataBound(objectsender,DataListItemEventArgse)
{
if(e.Item.ItemType==ListItemType.Item||e.Item.ItemTypeListItemType.AlternatingItem)
{
LinkButtonlbtn=(LinkButton)e.Item.FindControl("lbtndelete");
lbtn.Attributes.Add("OnClick","returnconfirm(‘确定要删除吗?
‘)");
}
}
protectedvoidDataGrid1_ItemDataBound(objectsender,DataGridItemEventArgse)
{
if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
{
LinkButtonlbtn=(LinkButton)e.Item.Cells[3].Controls[0];lbtn.Attributes.Add("OnClick","returnconfirm(‘确认删除?
‘)");
protectedvoidGridView1_RowDataBound(objectsender,GridViewRowEventArgse)
{if(e.Row.RowType==DataControlRowType.DataRow){
stringstrid=e.Row.Cells[0].Text;//获取第一行的字段值;e.Row.Cells[3].Attributes.Add("OnClick","returnconfirm(‘确认删除\""+strid+"\"?
‘)");
//用了两个转义符将第一列的值用引号括起来,注意转义符后面一个将不被解
释,是直接放上去;
}
}
ASP.NET程序中常用的三十三种代码
(1)
1.打开新的窗口并传送参数:
传送参数:
response.write("vscript>
window.open('ASPx?
id="+this.DropDownListl.Selectlndex+'&id1="+...+"v/script>))
接收参数:
stringa=Request.QueryString("id");
stringb=Request.QueryString("id1");
2.为按钮添加对话框
Button1.Attributes.Add("onclick","returnconfirm('确认?
')");
button.attributes.add("onclick","if(confirm('areyou
sure...?
')){returntrue;}else{returnfalse;}")
3.删除表格选定记录
intintEmplD=(int)MyDataGrid.DataKeys[e.ltem.ltemlndex];stringdeleteCmd="DELETEfromEmployeewhereemp_id="+intEmplD.ToString()
4.删除表格记录警告
privatevoidDataGrid_ltemCreated(Objectsender,DataGridltemEventArgse)
{
switch(e.ltem.ltemType)
{
caseListltemType.ltem:
caseListltemType.Alternatingltem:
caseListItemType.EditItem:
TableCellmyTableCell;myTableCell=e.Item.Cells[14];
LinkButtonmyDeleteButton;
myDeleteButton=(LinkButton)myTableCell.Controls[0];myDeleteButton.Attributes.Add("onclick","returnconfirm('您是否确定要删除这条信息');");
break;default:
break;
}
}
5.点击表格行链接另一页privatevoidgrdCustomer_ItemDataBound(objectsender,System.Web.UI.WebControls.DataGridItemEventArgse){
//点击表格打开if(e.Item.ItemType==ListItemType.Iteme.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.Iteme.Item.ItemType==ListItemType.AlternatingItem)
{stringOrderItemID=e.item.cells[1].Text;
e.item.Attributes.Add("ondblclick","location.href='../ShippedGrid.aspx?
id="+OrderItemID+"'");
<>
ASP.NET程序中常用的三十三种代码
(2)}双击表格打开新一页
if(e.Item.ItemType==ListItemType.Iteme.Item.ItemType==ListItemType.AlternatingItem)
{stringOrderItemID=e.item.cells[1].Text;
e.item.Attributes.Add("ondblclick","open('../ShippedGrid.aspx?
id="+OrderItemID+"')");
}
6.表格超连接列传递参数
vasp:
HyperLinkColumnTarget="_blank"headertext="ID号"
DataTextField="id"NavigateUrl="aaa.aspx?
id='
v%#DataBinder.Eval(Container.Dataltem,"数据字段1")%>'&name=
v%#DataBinder.Eval(Container.Dataltem,"数据字段2")%>'/>
7.表格点击改变颜色
if(e.ltem.ltemType==ListltemType.lteme.ltem.ltemType==ListltemType.Alternatingltem)
{e.ltem.Attributes.Add("onclick","this.style.backgroundColor='#99
cc00';
this.style.color='buttontext';this.style.cursor='default';");
}写在DataGrid的」temDataBound里
if(e.ltem.ltemType==ListltemType.lteme.ltem.ltemType==ListltemType.Alternatingltem)
{e.ltem.Attributes.Add("onmouseover","this.style.backgroundColor='#
99cc00';
this.style.color='buttontext';this.style.cursor='default';");e.ltem.Attributes.Add("onmouseout","this.style.backgroundColor='';t
his.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
//inglobal.asax
protectedvoidApplication_Error(Objectsender,EventArgse){
if(Server.GetLastError()isHttpUnhandledException)Server.Transfer("MyErrorPage.aspx");
//其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了:
)
}Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理
10.清空Cookie
<>
ASP.NET程序中常用的三十三种代码(3)
Cookie.EXPires=[DateTime];
Response.Cookies("UserName").Expires=0
11.自定义异常处理
//自定义异常处理类
usingSystem;
usingSystem.DiagnostiCS;
namespaceMyAppException
{///vsummary>
///从系统异常类ApplicationException继承的应用程序异常处理类。
///自动将异常内容记录到WindowsNT/2000的应用程序日志
///v/summary〉
publicclassAppException:
System.ApplicationException
{publicAppException()
{if(ApplicationConfiguration.EventLogEnabled)LogEvent("出
现一个未知错误。
");
}
publicAppException(stringmessage)
{LogEvent(message);
}
publicAppException(stringmessage,ExceptioninnerException)
{LogEvent(message);
if(innerException!
=null)
{LogEvent(innerException.Message);
}
}
//日志记录类
usingSystem;
usingSystem.Configuration;
usingSystem.Diagnostics;
usingSystem.IO;
usingSystem.Text;
usingSystem.Threading;
namespaceMyEventLog
{///vsummary〉
///事件日志记录类,提供事件日志记录支持
///vremarks〉
///定义了4个日志记录方法(error,warning,info,trace)
///v/remarks〉
///v/summary〉
publicclassApplicationLog
{///vsummary〉
///将错误信息记录到Win2000/NT事件日志中
///vparamname="message"〉需要记录的文本信息v/param〉
///v/summary〉
publicstaticvoidWriteError(Stringmessage)
{
WriteLog(TraceLevel.Error,message);
///vsummary>
///将警告信息记录到Win2000/NT事件日志中
///vparamname="message">需要记录的文本信息v/param>///v/summary〉
publicstaticvoidWriteWarning(Stringmessage)
{
WriteLog(TraceLevel.Warning,message);
<>
ASP.NET程序中常用的三十三种代码(4)}
///vsummary>
///将提示信息记录到Win2000/NT事件日志中
IIIvparamname="message">需要记录的文本信息v/param>
///v/summary>
publicstaticvoidWriteInfo(Stringmessage)
{
WriteLog(TraceLevel.Info,message);
}
///vsummary>
///将跟踪信息记录到Win2000/NT事件日志中
///vparamname="message">需要记录的文本信息v/param>
///v/summary>
publicstaticvoidWriteTrace(Stringmessage)
{
WriteLog(TraceLevel.Verbose,message);
}
///vsummary>
///格式化记录到事件日志的文本信息格式
///vparamname="ex">需要格式化的异常对象v/param>
///vparamname="catchInfo">异常信息标题字符串.v/param>
///vretvalue>
///vpara>格式后的异常信息字符串,包括异常内容和跟踪堆栈.v/para>
///v/retvalue>
///v/summary>
publicstaticStringFormatException(Exceptionex,StringcatchInfo)
{
StringBuilderstrBuilder=newStringBuilder();
if(catchInfo!
=String.Empty)
{strBuilder.Append(catchInfo).Append("\r\n");
}
strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace);
returnstrBuilder.ToString();
///vsummary>
///实际事件日志写入方法
///vparamname="level">要记录信息的级别(error,warning,info,trace).v/param>
///vparamname="messageText">要记录的文本.v/param>
///v/summary>
privatestaticvoidWriteLog(TraceLevellevel,StringmessageText)
{
try
{
EventLogEntryTypeLogEntryType;
switch(level)
{
caseTraceLevel.Error:
LogEntryType=EventLogEntryType.Error;break;
caseTraceLevel.Warning:
LogEntryType=EventLogEntryType.Warning;break;
caseTraceLevel.Info:
LogEntryType=EventLogEntryType.Information;break;
caseTraceLevel.Verbose:
LogEntryType=EventLogEntryType.SUCcessAudit;
ASP.NET程序中常用的三十三种代码(5)break;
default:
LogEntryType=EventLogEntryType.SuccessAudit;break;
}
EventLogeventLog=newEventLog("Application",
ApplicationConfiguration.EventLogMachineName,ApplicationConfiguration.EventLogSourceName);//写入事件日志
eventLog.WriteEntry(messageText,LogEntryType);
}
catch{}//忽略任何异常
}
}//classApplicationLog
}
12.Panel横向滚动,纵向自动扩展
vasp:
panelstyle="overflow-x:
scroll;overflow-y:
auto;">v/asp:
panel
13.回车转换成Tab
>
&&
''&&
vscriptlanguage="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.t