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&nbsp;Current<asp:Label ID="lbnCurrentPage" ForeColor=Red runat=server/>/<asp:Label ID="lblPageCount" ForeColor=red runat=server/>page&nbsp;
   
    <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>

发表评论

邮箱地址不会被公开。 必填项已用*标注