Panel & PlaceHolder控件的使用
Panel控件的属性:Visible,BackImageUrl,HorizontalAlign,Wrap
PlaceHolder控件在定义时不能向其中添加子控件,添加工作必须在程序中完成。这正是PlaceHolder控件存在的意义,可以根据程序的执行情况,动态的添加需要的控件,而Panel控件则不具体动态添加的功能。
PanelandPlaceHolder.aspx代码:
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”PanelandPlaceHolder.aspx.cs” Inherits=”PanelandPlaceHolder” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>无标题页</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Panel ID=”Panel1″ Wrap=true HorizontalAlign=Right runat=server>
<asp:Label Text=”This is first” runat=server/>
</asp:Panel>
<asp:Panel ID=”Panel2″ Wrap=true HorizontalAlign=Center runat=server>
<asp:Label Text=”This is second” runat=server/>
</asp:Panel>
<asp:Panel ID=”Panel3″ Wrap=true HorizontalAlign=Left runat=server>
<asp:Label Text=”This is third” runat=server/>
</asp:Panel>
<hr>
<asp:PlaceHolder ID=”Holder” runat=server/>
<hr>
Please choose the panel that you want:<br>
<asp:DropDownList ID=”DropDown” OnSelectedIndexChanged=”Selected” AutoPostBack=true runat=server>
<asp:ListItem>Panel1</asp:ListItem>
<asp:ListItem>Panel2</asp:ListItem>
<asp:ListItem>Panel3</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
PanelandPlaceHolder.aspx.cs代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
public partial class PanelandPlaceHolder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
}
}
public void Selected(object sender, EventArgs e)
{
Panel p = (Panel)FindControl(DropDown.SelectedItem.Text);
p.Visible = true;
p.ForeColor =Color.Red;
string selindex = DropDown.SelectedIndex.ToString();
Label lbl = new Label();
switch (selindex)
{
case “0″:
lbl.Text=”You selected Panel1″;
break;
case “1″:
lbl.Text=”You selected Panel2″;
break;
case “2″:
lbl.Text=”You selected Panel3″;
break;
default:
lbl.Text=”You haven’t selected anyone”;
break;
}
Holder.Controls.Add(lbl);
}
}
Tags: Asp.net
文件上传
利用HtmlInputFile控件进行文件上传
用到的属性:PostedFile
HttpPostedFile是System.Web命名空间中的一个类,它的属性和方法包括:ContentLength,ContentType,FileName,InputStream,SaveAs
1,首先通过HtmlInputFile控件的PostedFile属性建立HttpPostedFile实例
2,通过HttpPostedFile的FileName属性取得文件名
3,通过HttpPostedFile的SaveAs方法进行保存
同时可以通过ContentLength,ContentType属性取得文件长度和文件类型。
代码(用code-behind进行代码分离):
说明:亲密接触Asp.net教材中提到,使用Code-behind进行代码分离时要在.cs文件中对主文件中的Html控件进行声明。但实践发现,使用vs2005创建web form后vs会自动进行主文件和后台.cs文件的关联,不需要特别声明。
DoUpload.aspx代码:
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”DoUpLoad.aspx.cs” Inherits=”DoUpLoad” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>无标题页</title>
</head>
<body>
<form id=”form1″ enctype=”multipart/form-data” runat=”server”>
<div>
Please choose the file that you want to upload:<Input type=file id=”UpLoadFile” runat=server><br>
<Input type=submit value=”UpLoad” onserverclick=”UpLoad” runat=server>
<hr>
Uploaded filename:<asp:Label ID=”FileName” Text=”UnUpload” runat=server/><br>
File size:<asp:Label ID=”FileSize” Text=”UnUpload” runat=server/><br>
Real Filename:<asp:Label ID=”rFileName” Text=”UnUpload” runat=server/><br>
File Type:<asp:Label ID=”FileType” Text=”UnUpload” runat=server/><br>
Content of InputStream:<asp:Label ID=”InputStream” Text=”UnUpload” runat=server/>
</div>
</form>
</body>
</html>
DoUpload.aspx.cs代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class DoUpLoad : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UpLoadFile.MaxLength = 5300493;
UpLoadFile.Size = 20;
}
public void UpLoad(object sender, EventArgs e)
{
HttpPostedFile hpf = UpLoadFile.PostedFile;
FileName.Text = hpf.FileName;
FileSize.Text = hpf.ContentLength.ToString();
FileType.Text = hpf.ContentType.ToString();
InputStream.Text = hpf.InputStream.ToString();
char[] de ={ ‘\\’ };
string[] AFileName = hpf.FileName.Split(de);
string strFileName = AFileName[AFileName.Length - 1];
rFileName.Text = strFileName;
hpf.SaveAs(Server.MapPath(”.”) + “\\UpLoadFile\\” + strFileName);
}
}
问题点:在测试的时候发现,大文件上传时会出错。google了一下
思归提供了
解决办法,但作为一个初学者,没有完整的代码,看不大懂。
下边是在itepub.net里有完整代码的解决办法,原文地址:http://www.itepub.net/html/kaifajingcui/Asp_Net/2006/0828/41240.html
在这里保存一下,以后查阅起来方便点。
利用隐含的HttpWorkerRequest用它的GetPreloadedEntityBody 和 ReadEntityBody方法处理文件流
HttpApplication application1 = sender as HttpApplication;
HttpWorkerRequest request1 = (HttpWorkerRequest) ((IServiceProvider) HttpContext.Current).GetService(typeof(HttpWorkerRequest));
try
{
if (application1.Context.Request.ContentType.IndexOf(”multipart/form-data”) <= -1)
{
return;
}
//Check The HasEntityBody
if (!request1.HasEntityBody())
{
return;
}
int num1 = 0;
TimeSpan span1 = DateTime.Now.Subtract(this.beginTime);
string text1 = application1.Context.Request.ContentType.ToLower();
byte[] buffer1 = Encoding.ASCII.GetBytes((”\r\n–” + text1.Substring(text1.IndexOf(”boundary=”) + 9)).ToCharArray());
int num2 = Convert.ToInt32(request1.GetKnownRequestHeader(11));
Progress progress1 = new Progress();
application1.Context.Items.Add(”FileList”, new Hashtable());
byte[] buffer2 = request1.GetPreloadedEntityBody();
num1 += buffer2.Length;
string text2 = this.AnalysePreloadedEntityBody(buffer2, “UploadGUID”);
if (text2 != string.Empty)
{
application1.Context.Items.Add(”LionSky_UpLoadModule_UploadGUID”, text2);
}
bool flag1 = true;
if ((num2 > this.UpLoadFileLength()) && ((0 > span1.TotalHours) || (span1.TotalHours > 3)))
{
flag1 = false;
}
if ((0 > span1.TotalHours) || (span1.TotalHours > 3))
{
flag1 = false;
}
string text3 = this.AnalysePreloadedEntityBody(buffer2, “UploadFolder”);
ArrayList list1 = new ArrayList();
RequestStream stream1 = new RequestStream(buffer2, buffer1, null, RequestStream.FileStatus.Close, RequestStream.ReadStatus.NoRead, text3, flag1, application1.Context, string.Empty);
list1.AddRange(stream1.ReadBody);
if (text2 != string.Empty)
{
progress1.FileLength = num2;
progress1.ReceivedLength = num1;
progress1.FileName = stream1.OriginalFileName;
progress1.FileCount = ((Hashtable) application1.Context.Items["FileList"]).Count;
application1.Application["_UploadGUID_" + text2] = progress1;
}
if (!request1.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer4;
ArrayList list2;
int num3 = 204800;
byte[] buffer3 = new byte[num3];
while ((num2 - num1) >= num3)
{
if (!application1.Context.Response.IsClientConnected)
{
this.ClearApplication(application1);
}
num3 = request1.ReadEntityBody(buffer3, buffer3.Length);
num1 += num3;
list2 = stream1.ContentBody;
if (list2.Count > 0)
{
buffer4 = new byte[list2.Count + buffer3.Length];
list2.CopyTo(buffer4, 0);
buffer3.CopyTo(buffer4, list2.Count);
stream1 = new RequestStream(buffer4, buffer1, stream1.FileStream, stream1.FStatus, stream1.RStatus, text3, flag1, application1.Context, stream1.OriginalFileName);
}
else
{
stream1 = new RequestStream(buffer3, buffer1, stream1.FileStream, stream1.FStatus, stream1.RStatus, text3, flag1, application1.Context, stream1.OriginalFileName);
}
list1.AddRange(stream1.ReadBody);
if (text2 != string.Empty)
{
progress1.ReceivedLength = num1;
progress1.FileName = stream1.OriginalFileName;
progress1.FileCount = ((Hashtable) application1.Context.Items["FileList"]).Count;
application1.Application["_UploadGUID_" + text2] = progress1;
}
}
buffer3 = new byte[num2 - num1];
if (!application1.Context.Response.IsClientConnected && (stream1.FStatus == RequestStream.FileStatus.Open))
{
this.ClearApplication(application1);
}
num3 = request1.ReadEntityBody(buffer3, buffer3.Length);
list2 = stream1.ContentBody;
if (list2.Count > 0)
{
buffer4 = new byte[list2.Count + buffer3.Length];
list2.CopyTo(buffer4, 0);
buffer3.CopyTo(buffer4, list2.Count);
stream1 = new RequestStream(buffer4, buffer1, stream1.FileStream, stream1.FStatus, stream1.RStatus, text3, flag1, application1.Context, stream1.OriginalFileName);
}
else
{
stream1 = new RequestStream(buffer3, buffer1, stream1.FileStream, stream1.FStatus, stream1.RStatus, text3, flag1, application1.Context, stream1.OriginalFileName);
}
list1.AddRange(stream1.ReadBody);
if (text2 != string.Empty)
{
progress1.ReceivedLength = num1 + buffer3.Length;
progress1.FileName = stream1.OriginalFileName;
progress1.FileCount = ((Hashtable) application1.Context.Items["FileList"]).Count;
if (flag1)
{
progress1.UploadStatus = Progress.UploadStatusEnum.Uploaded;
}
else
{
application1.Application.Remove(”_UploadGUID_” + text2);
}
}
}
byte[] buffer5 = new byte[list1.Count];
list1.CopyTo(buffer5);
this.PopulateRequestData(request1, buffer5);
}
catch (Exception exception1)
{
this.ClearApplication(application1);
throw exception1;
}
Tags: Asp.net
Global.asax文件
Global.asax总共有7个事件,分别为:
Application_Start,Application_End,Application_BeginRequest,Application_EndRequest,Application_Error
Session_Start,Session_End
代码:
实现功能:1,利用Application对象定义一个全局变量 同时用Application_Start事件在应用程序开始被请求的时候就将其初始化 2,利用Application_BeginRequest统计访问量 3,利用Session_Start事件统计在线人数
Global.asax
<%@ Application Language=”C#” %>
<script runat=”server”>
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
String Myconnstring = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + Server.MapPath(”.”) + “..\\data\\score.mdb;”;
Application["ConnString"] = Myconnstring;
Application["PageViewer_Count"]=0;
Application["Online_Count"]=0;
}
void Application_BeginRequest(object sender, EventArgs e)
{
Application["PageViewer_Count"] = (Int32)Application["PageViewer_Count"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
Application["Online_Count"] = (Int32)Application["Online_Count"] + 1;
}
void Session_End(object sender, EventArgs e)
{
Application["Online_Count"] = (Int32)Application["Online_Count"] - 1;
}
</script>
UseforGlobal.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”UseforGlobal.aspx.cs” Inherits=”UseforGlobal” %>
<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.OleDb” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<script runat=server>
OleDbConnection Myconn;
public void Page_Load(Object src, EventArgs e)
{
string Myconnstring = (string)Application["ConnString"];
Myconn = new OleDbConnection(Myconnstring);
Myconn.Open();
PageViewer_Count.Text = Application["PageViewer_Count"].ToString();
Online_Count.Text = Application["Online_Count"].ToString();
Data_Bind();
}
ICollection DataSource()
{
string strsel = “select * from score”;
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(strsel, Myconn);
DataSet ds = new DataSet();
MyAdapter.Fill(ds, “score”);
return ds.Tables["score"].DefaultView;
}
public void Data_Bind()
{
score.DataSource = DataSource();
score.DataBind();
}
</script>
<title>UseforGolbal</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:DataGrid ID=”score” runat=server>
<Columns>
<asp:BoundColumn HeaderText=”Name” DataField=”s_Name”/>
</Columns>
</asp:DataGrid><br><br>
PageViewer_Count:<asp:Label ID=”PageViewer_Count” runat=server/><br><br>
Online_Count:<asp:Label ID=”Online_Count” runat=server/>
</div>
</form>
</body>
</html>
Tags: Asp.net
Application,Session,Cookie
Application:设置全局变量,所设变量在整个应用程序范围内有效。
有 Application.Lock() and Application.UnLock() 两个方法。
Session:在Asp中session要依赖于cookie才可运行,但在Asp.net中设置web.config sessionState cookieless="true"则可使session不依赖于cookie
Cookie:实例化一个cookie HttpCookie xxx=new HttpCookie("xxx")
设置单值的cookie,cookie.Value="xxx"
设置多值的cookie,cookie.Value.Add("KeyWord","value")
应用cookie Response.AppendCookie("cookiename")
读取cookie HttpCookie xxx=Request.Cookies("xxx")
设置cookie的过期时间
DateTime xxx=DateTime.Now;
TimeSpan xx=new TimeSpan(x,x,x,x) 分别为天,小时,分钟,秒
cookie.Expires=xxx.Add(xx)
代码:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script runat=server>
//Application的应用
public void Page_Load(Object src, EventArgs e)
{
Application.Lock();
Application["User_Count"] = (Int32)Application["User_Count"] + 1;
Application.UnLock();
Count.Text = Application["User_Count"].ToString();
//设置session
Session["Name"] = "John";
Name.Text = Session["Name"].ToString();
//建立一个cookie实例,并对其赋值
HttpCookie cookie = new HttpCookie("John");
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(0, 0, 2, 0);
cookie.Expires = dt.Add(ts);
cookie.Values.Add("name", "John");
cookie.Values.Add("age", "26");
cookie.Values.Add("sex", "male");
Response.AppendCookie(cookie);
//读取cookie
HttpCookie readcookie = Request.Cookies["John"];
cookie1.Text = readcookie.Values["name"].ToString();
cookie2.Text=readcookie.Values["age"].ToString();
cookie3.Text = readcookie.Values["sex"].ToString();
}
</script>
<title>Application</title>
</head>
<body>
<form id="form1" runat="server">
<div>
The count of viewer is:<asp:Label ID="Count" ForeColor=red runat=server/><br>
Example of Session,Name is:<asp:Label ID="Name" ForeColor=blue runat=server/>
<br>Name:<asp:Label ID="cookie1" runat=server/><br>
Age:<asp:Label ID="cookie2" runat=server/><br>
Sex:<asp:Label ID="cookie3" runat=server/><br>
</div>
</form>
</body>
</html>
Tags: Asp.net
DataList控件
包含的模板:ItemTemplate,HeaderTemplate,FooterTemplate,AlternatingItemTemplate,SeparatorTemplate,SelectedItemTemplate,EditItemTemplate
同时DataList控件提供了Repeater不具备的RepeatDriection and RepeatColumns属性
RepeatDirection可以取两个值:Horizontal and Vertical(默认为Vertical)
学习内容:SelectedItemTemplate,EditItemTemplate
注意:在OnItemCommand的响应函数中score.SelectedIndex=e.Item.ItemIndex这句如果没有的话,也可以正常运行,只是在最后的结果中要点击连接两次才会显示SelectedItemTemplate中的内容。
代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataGridSort.aspx.cs" Inherits="DataGridSort" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script runat=server>
OleDbConnection Myconn;
public void Page_Load(Object src, EventArgs e)
{
//连接语句
string Myconnstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(".") + "..\\data\\score.mdb;";
Myconn = new OleDbConnection(Myconnstring);
Myconn.Open();
if (!IsPostBack)
{
BindGrid();
}
}
//创建默认视图
ICollection Createtable()
{
string strsel = "select * from score";
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(strsel, Myconn);
DataSet ds=new DataSet();
MyAdapter.Fill(ds, "score");
return ds.Tables["score"].DefaultView;
}
//数据绑定
public void BindGrid()
{
score.DataSource = Createtable();
score.DataBind();
}
//select命令响应函数
public void DataList_ItemCommand(Object sender, DataListCommandEventArgs e)
{
score.SelectedIndex = e.Item.ItemIndex;
BindGrid();
}
//编辑命令响应函数
public void DataList_EditCommand(Object sender, DataListCommandEventArgs e)
{
score.EditItemIndex = e.Item.ItemIndex;
BindGrid();
}
//取消命令响应函数
public void DataList_CancelCommand(Object sender, DataListCommandEventArgs e)
{
score.EditItemIndex = -1;
BindGrid();
}
//更新命令响应函数
public void DataList_UpdateCommand(Object sender, DataListCommandEventArgs e)
{
string strname=((Label)e.Item.FindControl("lblname")).Text;
int intmath=Int32.Parse(((TextBox)e.Item.FindControl("tbmath")).Text);
int intenglish=Int32.Parse(((TextBox)e.Item.FindControl("tbenglish")).Text);
int intchinese=Int32.Parse(((TextBox)e.Item.FindControl("tbchinese")).Text);
string strupdate = "Update score set s_Math=" +intmath+ ",s_English=" +intenglish+ ",s_Chinese=" +intchinese+ " where s_Name=’" +strname+ "’";
OleDbCommand Mycommand = new OleDbCommand(strupdate, Myconn);
Mycommand.ExecuteNonQuery();
score.EditItemIndex = -1;
BindGrid();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="score"
HeaderStyle-BackColor=ActiveCaptionText
AlternatingItemStyle-BackColor=ActiveCaption
runat=server
OnItemCommand="DataList_ItemCommand"
OnEditCommand="DataList_EditCommand"
OnCancelCommand="DataList_CancelCommand"
OnUpdateCommand="DataList_UpdateCommand"
SelectedItemStyle-BackColor=red
RepeatLayout=Table>
<ItemTemplate>
Name:<%# DataBinder.Eval(Container.DataItem,"s_Name") %>
<asp:LinkButton Text="Details" id="btnselect" CommandName="select" runat=server/>
<asp:LinkButton Text="Edit" ID="btnedit" CommandName="edit" runat=server/>
</ItemTemplate>
<SelectedItemTemplate>
Name:<%# DataBinder.Eval(Container.DataItem,"s_Name") %><br>
Math:<%# DataBinder.Eval(Container.DataItem,"s_Math") %><br>
English:<%# DataBinder.Eval(Container.DataItem,"s_English") %><br>
Chinese:<%# DataBinder.Eval(Container.DataItem,"s_Chinese") %><br>
</SelectedItemTemplate>
<EditItemTemplate>
Name:<asp:Label ID="lblname" Text=’<%# DataBinder.Eval(Container.DataItem,"s_Name") %>’ runat=server/><br>
Math:<asp:TextBox ID="tbmath" Text=’<%# DataBinder.Eval(Container.DataItem,"s_Math") %>’ runat=server/><br>
English:<asp:TextBox ID="tbenglish" Text=’<%# DataBinder.Eval(Container.DataItem,"s_English") %>’ runat=server/><br>
Chinese:<asp:TextBox ID="tbchinese" Text=’<%# DataBinder.Eval(Container.DataItem,"s_Chinese") %>’ runat=server/><br>
<asp:LinkButton ID="lblupdate" Text="Update" CommandName="Update" runat=server/>
<asp:LinkButton ID="lblcancel" Text="Cancel" CommandName="Cancel" runat=server/>
</EditItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
DataList的分页功能
现在的水平,程序只能照教材抄,自己来理一下程序的思路。
注:在程序调试的过程中,在return ds.Tables["score"].DefaultView处出现了一个错误,提示“需要输入符号”,当时没能解决,关了电脑,除去吃了个饭,回来再打开,调试,ok了。
1,分页所需要的数据:PageSize,PageCount,RecordCount,PageIndex,CurrentPage(给ViewState["PageIndex"]付值用)
2,编写函数去得到相应数据
3,首先通过StartIndex取得需要显示的页的第一条记录的Index值 StartIndex=CurrentPage*PageSize
然后通过MyAdapter.Fill()方法获得要显示的页的默认视图MyAdapter.Fill(ds,StartIndex,PageSize,"score")
4, 绑定数据。对是否是首页或是末页进行判断(通过CurrentPage<PageCount-1 and CurrentPage>0进行判断),如果是首页则设置lbnPrevPage.Enabled=false,如果是末页则设置 lbnNextPage.Enabled=false
5,使用swith case函数对要进行上翻页还是下翻页进行判断,上翻和下翻的命令用e.CommandName来取得
6,最后设置ViewState["PageIndex"]=CurrentPage
代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataListPageIndex.aspx.cs" Inherits="DataListPageIndex" %>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.OleDb"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script runat=server>
OleDbConnection Myconn;
int PageSize, ItemCount, RecordCount, PageCount, CurrentPage;
public void Page_Load(Object src, EventArgs e)
{
PageSize = 2;
//连接语句
string Myconnstring="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(".")+"..\\data\\score.mdb;";
Myconn=new OleDbConnection(Myconnstring);
Myconn.Open();
//第一次请求执行
if (!IsPostBack)
{
ListBind();
CurrentPage = 0;
ViewState["PageIndex"] = 0;
//计算记录条数
RecordCount = CalculateRecord();
lblRecordCount.Text = RecordCount.ToString();
//计算总共有多少页
PageCount = RecordCount / PageSize;
lblPageCount.Text = PageCount.ToString();
ViewState["PageCount"] = PageCount;
}
}
//计算记录条数
public int CalculateRecord()
{
int intCount;
string strCount = "select Count(*) as co from score";
OleDbCommand Mycommand = new OleDbCommand(strCount, Myconn);
OleDbDataReader dr = Mycommand.ExecuteReader();
if (dr.Read())
{
intCount = Int32.Parse(dr["co"].ToString());
}
else
{
intCount = 0;
}
dr.Close();
return intCount;
}
//创建数据源
ICollection DataSource()
{
//设定读取的起始位置
int startindex;
startindex = CurrentPage*PageSize;
string strsel="select * from score";
OleDbDataAdapter MyAdapter=new OleDbDataAdapter(strsel,Myconn);
DataSet ds=new DataSet();
MyAdapter.Fill(ds,startindex,PageSize,"score");
return ds.Tables["score"].DefaultView;
}
//数据绑定
public void ListBind()
{
score.DataSource = DataSource();
score.DataBind();
lbnNextPage.Enabled = true;
lbnPrevPage.Enabled = true;
if (CurrentPage == PageCount - 1) lbnNextPage.Enabled = false;
if (CurrentPage == 0) lbnPrevPage.Enabled = false;
lbnCurrentPage.Text = (CurrentPage + 1).ToString();
}
//Page_OnClick事件处理
public void Page_OnClick(Object sender,CommandEventArgs e)
{
PageCount = (int)ViewState["PageCount"];
CurrentPage = (int)ViewState["PageIndex"];
//判断翻页方向
string cmd=e.CommandName;
switch(cmd)
{
case "Next":
if(CurrentPage<(PageCount-1)) CurrentPage++;
break;
case "Prev":
if(CurrentPage>0) CurrentPage–;
break;
}
ViewState["PageIndex"]=CurrentPage;
ListBind();
}
</script>
<title>DataListPageIndex</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Total<asp:Label ID="lblRecordCount" runat=server/>record Current<asp:Label ID="lbnCurrentPage" ForeColor=Red runat=server/>/<asp:Label ID="lblPageCount" ForeColor=red runat=server/>page
<asp:DataList ID="score" AlternatingItemStyle-BackColor=ControlDarkDark HeaderStyle-BackColor=AntiqueWhite runat=server>
<ItemTemplate>
Name:<%# DataBinder.Eval(Container.DataItem,"s_Name")%>
</ItemTemplate>
</asp:DataList>
<asp:LinkButton ID="lbnPrevPage" OnCommand="Page_OnClick" CommandName="Prev" runat=server Text="PrevPage"/>
<asp:LinkButton ID="lbnNextPage" OnCommand="Page_OnClick" CommandName="Next" runat=server Text="NextPage"/>
</div>
</form>
</body>
</html>
Tags: Asp.net
DataGrid 控件
用到的属性 :AllowSorting,OnSortCommand
6.用Sort方法进行排序
注意:如果要设置排序数序(DESC),则在IsPostBack函数中必须指定默认的排序字段,否则会出现找不到DESC字段错误。
if (!IsPostBack)
{
ViewState["SortField"] = "s_Name";
BindGrid();
}
Sort方法的代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataGridSort.aspx.cs" Inherits="DataGridSort" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script runat=server>
OleDbConnection Myconn;
public void Page_Load(Object src, EventArgs e)
{
string Myconnstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(".") + "..\\data\\score.mdb;";
Myconn = new OleDbConnection(Myconnstring);
Myconn.Open();
if (!IsPostBack)
{
ViewState["SortField"] = "s_Name";
BindGrid();
}
}
ICollection Createtable()
{
string strsel = "select * from score";
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(strsel, Myconn);
DataSet ds=new DataSet();
MyAdapter.Fill(ds, "score");
return ds.Tables["score"].DefaultView;
}
public void BindGrid()
{
DataView dv = (DataView)Createtable();
dv.Sort = (string)ViewState["SortField"]+" DESC";
score.DataSource = dv;
score.DataBind();
}
public void DataGrid_Sort(Object Sender, DataGridSortCommandEventArgs e)
{
ViewState["SortField"] = (string)e.SortExpression;
BindGrid();
}
</script>
<title>DataGridSort</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataGrid ID="score" AutoGenerateColumns=false HeaderStyle-BackColor=ActiveCaption AlternatingItemStyle-BackColor=AliceBlue AllowSorting=true OnSortCommand="DataGrid_Sort" runat=server>
<Columns>
<asp:BoundColumn HeaderText="Name" DataField="s_Name" SortExpression="s_Name" ReadOnly=true/>
<asp:BoundColumn HeaderText="Math" DataField="s_Math" SortExpression="s_Math"/>
<asp:BoundColumn HeaderText="English" DataField="s_English" SortExpression="s_English"/>
<asp:BoundColumn HeaderText="Chinese" DataField="s_Chinese" SortExpression="s_Chinese"/>
</Columns>
</asp:DataGrid>
</div>
</form>
</body>
</html>
Repeater控件
Repeater控件的五种模板:HeaderTemplate,ItemTemplate,AlternatingItemTemplate,SeparatorTemplate,FooterTemplate
Repeater控件的代码
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css" class="1">
<!–
a:link { text-decoration: none}
a:active { text-decoration: none }
a:visited { text-decoration: none }
–>
</style>
<script language="c#" runat="server">
public void Page_Load(Object src,EventArgs e)
{
string Myconnstring="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(".")+".\\data\\score.mdb;";
OleDbConnection Myconn=new OleDbConnection(Myconnstring);
Myconn.Open();
string strsel="select * from score";
OleDbDataAdapter MyAdapter=new OleDbDataAdapter(strsel,Myconn);
DataSet ds=new DataSet();
MyAdapter.Fill(ds,"score");
score.DataSource=ds;
score.DataMember="score";
score.DataBind();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>DataGrid</title>
</head>
<body>
<form id="Form1" runat="server">
<asp:Repeater id="score" runat="server">
<HeaderTemplate>
This is Header<br>
</HeaderTemplate>
<ItemTemplate>
Name:<%# DataBinder.Eval(Container.DataItem,"s_Name")%><br>
Chinese:Name:<%# DataBinder.Eval(Container.DataItem,"s_Chinese")%><br>
</ItemTemplate>
<AlternatingItemTemplate>
Name:<font color=red><%# DataBinder.Eval(Container.DataItem,"s_Name")%></font><br>
Chinese:Name:<font color=red><%# DataBinder.Eval(Container.DataItem,"s_Chinese")%></font><br>
</AlternatingItemTemplate>
<SeparatorTemplate>
<hr>
</SeparatorTemplate>
<FooterTemplate>
This is Footer
</FooterTemplate>
</asp:Repeater>
</form>
</body>
<html>
</html>
Tags: Asp.net
DataGrid 控件
用到的DataGrid属性:OnEditCommand,OnUpdateCommand,OnCancelCommand
4.EditCommandColumn
用到的属性:HeaderText,EditText,CancelText,UpdateText,ButtonType
注意:在定义return ds.Tables["score"].DefaultView表名的时候,一定要和数据库所使用表名一致。在不一直的情况下,Edit和Cancel函数可以正常执行,但在执行Update函数时会出错。
今天的代码:
<%@ Page Language=”C#” ContentType=”text/html” ResponseEncoding=”gb2312″ %>
<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.OleDb” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<script runat=server>
OleDbConnection Myconn;
public void Page_Load(Object sender, EventArgs e)
{
// 连接语句
string Myconnstring = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + Server.MapPath(”.”) + “..\\data\\score.mdb;”;
Myconn = new OleDbConnection(Myconnstring);
Myconn.Open();
if (!Page.IsPostBack)
{
BindGrid();
}
}
//创建当前数据的默认视图
ICollection CreateTable()
{
string strsel = “select * from score”;
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(strsel, Myconn);
DataSet ds = new DataSet();
MyAdapter.Fill(ds, “score”);
return ds.Tables["score"].DefaultView;
}
public void BindGrid()
{
score.DataSource = CreateTable();
score.DataBind();
}
//处理Edit命令
public void DataGrid_EditCommand(Object sender, DataGridCommandEventArgs e)
{
score.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}
//处理Cancel命令
public void DataGird_CancelCommand(Object sender, DataGridCommandEventArgs e)
{
score.EditItemIndex = -1;
BindGrid();
}
//处理Update命令
public void DataGrid_UpdateCommand(Object sender, DataGridCommandEventArgs e)
{
//取得已更新数据
string strname = e.Item.Cells[1].Text;
int intmath = Int32.Parse(((TextBox)e.Item.Cells[2].Controls[0]).Text);
int intenglish = Int32.Parse(((TextBox)e.Item.Cells[3].Controls[0]).Text);
int intchinese = Int32.Parse(((TextBox)e.Item.Cells[4].Controls[0]).Text);
//更新数据库
string strupdate=”Update score set s_Math=”+intmath+”,s_English=”+intenglish+”,s_Chinese=”+intchinese+” Where s_name=’”+strname+”‘”;
OleDbCommand Mycommand = new OleDbCommand(strupdate, Myconn);
Mycommand.ExecuteNonQuery();
score.EditItemIndex = -1;
BindGrid();
}
</script>
<title>EditCommandColumn</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:DataGrid ID=”score” runat=server HeaderStyle-BackColor=”#aaaadd” AlternatingItemStyle-BackColor=”#addeae” AutoGenerateColumns=false OnEditCommand=”DataGrid_EditCommand” OnCancelCommand=”DataGird_CancelCommand” OnUpdateCommand=”DataGrid_UpdateCommand”>
<Columns>
<asp:EditCommandColumn HeaderText=”Play area” EditText=”Edit” CancelText=”Cancel” UpdateText=”Update” ButtonType=”PushButton”/>
<asp:BoundColumn HeaderText=”Name” DataField=”s_name” ReadOnly=true/>
<asp:BoundColumn HeaderText=”Math” DataField=”s_Math”/>
<asp:BoundColumn HeaderText=”English” DataField=”s_English”/>
<asp:BoundColumn HeaderText=”Chinese” DataField=”s_Chinese”/>
</Columns>
</asp:DataGrid>
</div>
</form>
</body>
</html>
</html>
Tags: Asp.net
DataGrid 控件
用到的属性:AllowPaging,PageSize,OnPageIndexChanged
5.用DataGrid控件进行分页
注意:不是所有的控件都可以进行DataBind(),在使用DataBind之前先用ICollection函数创建默认视图,然后再进行DataBind()
声明OleDbConnection变量位全局变量
今天的代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataGridPageIndex.aspx.cs" Inherits="DataGridPageIndex" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script runat=server>
OleDbConnection Myconn;
public void Page_Load(Object src, EventArgs e)
{
string Myconnstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(".") + "..\\data\\score.mdb;";
Myconn = new OleDbConnection(Myconnstring);
Myconn.Open();
if (!Page.IsPostBack)
{
DataBind();
}
}
ICollection CreateTable()
{
string strsel = "select * from score";
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(strsel, Myconn);
DataSet ds = new DataSet();
MyAdapter.Fill(ds, "score");
return ds.Tables["score"].DefaultView;
}
public void DataBind()
{
score.DataSource = CreateTable();
score.DataBind();
}
public void DataGrid_PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
score.CurrentPageIndex = e.NewPageIndex;
DataBind();
}
</script>
<title>DataGridPageIndex</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataGrid
HeaderStyle-BackColor=Aqua
AlternatingItemStyle-BackColor=AliceBlue
ID="score"
AutoGenerateColumns=true
runat=server
AllowPaging=true PageSize="3"
OnPageIndexChanged="DataGrid_PageChanged">
</asp:DataGrid>
</div>
</form>
</body>
</html>
</html>
Tags: Asp.net
DataGrid 控件 (学习DataGrid Column 的5种类型)
用到的DataGrid属性:id,runat,HeaderStyle-BackColor,AlternatingItemStyle-BackColor,AutoGenerateColumns,OnItemCommand
1.BoundColumn
用到的属性:DataField,HeaderText
2.HyperLinkColumn
用到的属性:HeaderText,DataTextField,DataNavigateUrlField,DataNavigateUrlFormatString
3.ButtonColumn
用到的属性:HeaderText,Text,ButtonType
ButtonType在使用的过程中出现了问题,当设置ButtonType=PushButton时调试出错:System.ArgumentException: 回发或回调参数无效
(明天再研究)
今天的代码
<%@ Page Language=”C#” ContentType=”text/html” ResponseEncoding=”gb2312″ %>
<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.OleDb” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<script language=”c#” runat=”server”>
public void Page_Load(Object src,EventArgs e)
{
string Myconnstring=”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=”+Server.MapPath(”.”)+”.\\data\\score.mdb;”;
OleDbConnection Myconn=new OleDbConnection(Myconnstring);
Myconn.Open();
string strsel=”select * from score”;
OleDbDataAdapter MyAdapter=new OleDbDataAdapter(strsel,Myconn);
DataSet ds=new DataSet();
MyAdapter.Fill(ds,”table1″);
score.DataSource=ds;
score.DataMember=”table1″;
score.DataBind();
}
public void DataGrid_ItemCommand(Object sender,DataGridCommandEventArgs e)
{
TableRow tr=e.Item;
lblname.Text=tr.Cells[1].Text;
lblmath.Text=tr.Cells[2].Text;
lblenglish.Text=tr.Cells[3].Text;
lblchinese.Text=tr.Cells[4].Text;
}
</script>
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″ />
<title>DataGrid</title>
</head>
<body>
<table>
<tr>
<td>
<form runat=”server” action=”BoundColumn.aspx” method=”get”>
<asp:DataGrid id=”score” runat=”server”
HeaderStyle-BackColor=”#666666″
AlternatingItemStyle-BackColor=”#99CC00″
AutoGenerateColumns=”false”
OnItemCommand=”DataGrid_ItemCommand”
>
<Columns>
<asp:ButtonColumn HeaderText=”Play area” Text=”Show details” ButtonType=”PushButton” />
<asp:HyperLinkColumn HeaderText =”Name” DataTextField=”s_Name” DataNavigateUrlField=”s_Name” DataNavigateUrlFormatString=”boundcolumn.aspx?name={0}”/>
<asp:BoundColumn DataField=”s_Math” HeaderText=”Math Score”/>
<asp:BoundColumn DataField=”s_English” HeaderText=”English Score”/>
<asp:BoundColumn DataField=”s_Chinese” HeaderText=”Chinese Score”/>
</Columns>
</asp:DataGrid>
</form>
</td>
<td valign=”top”>
<table>
<tr><td>Chosed name</td><td><asp:Label ID=”lblname” runat=”server”/></td></tr>
<tr><td>Math</td><td><asp:Label ID=”lblmath” runat=”server”/></td></tr>
<tr><td>English</td><td><asp:Label ID=”lblenglish” runat=”server”/></td></tr>
<tr><td>Chinese</td><td><asp:Label ID=”lblchinese” runat=”server”/></td></tr>
<td>
</table>
</tr>
</table>
</body>
</html>
Tags: Asp.net