如何使数据绑定的控件实现“上一条”、“下一条”、“第一条”和“最后一条”的功能?(WinForm, C#)(06年的文章,技术已过时)

 

有“类别”表,数据如下:     
 
有“产品”表,数据如下:(只是其中的一部分数据)
 
在界面上要求显示的效果如下:
单击上一条、下一条、第一条和最后一条的按钮,或者任意输入一个数值,文本框和 DataGrid 就会显示想应的记录。
怎样实现呢?可以分两步完成:
1.            因为导航条
        在每个页面都有,所以先来制作一个自定义控件吧。
2.           将数据 绑定到文本框和 DataGrid
 
 
 
在解决方案中添加一个windows应用程序,如图所示:
UserControl.cs中添加控件,如图所示:
 
.cs文件中添加各个按钮的委托和事件:
        public delegate void  zuiqian();
        public delegate void xiangqian();
        public delegate void zuihou();
        public delegate void xianghou();
        public delegate void total();
        public event zuiqian zq;
        public event xiangqian xq;
        public event zuihou zh;
        public event xianghou xh;
        public event total tl;
        
private void zuiqianBt_Click(object sender, System.EventArgs e)
        {
            if(zq!=null)
                zq();
        }
 
        private void qianBt_Click(object sender, System.EventArgs e)
        {
        if(xq!=null)
            xq();
        }
 
       
        private void houBt_Click(object sender, System.EventArgs e)
        {
            if(xh!=null)
                xh();
        }
 
       
        private void zuihouBt_Click(object sender, System.EventArgs e)
        {
        if(zh!=null)
            zh();
        }
 
       
        private void totalBt_Click(object sender, System.EventArgs e)
        {
        if(tl!=null)
            tl();
        }
在解决方案下再添加一个windows应用程序,如图所示:
zdykj/bin/Debug下的zdykj.dll加入到工具箱中,在把UserControl拖入到SortForm页面中。
SortForm.cs文件的代码如下:(蓝色为重点)
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
 
namespace SellManage
{
    ///<summary>
    /// SortForm 的摘要说明。
    ///</summary>
    public class SortForm : System.Windows.Forms.Form
    {
        sqlDB sqldb = new sqlDB();
        private DataSet ds;
        private System.Windows.Forms.Label lm;
        private System.Windows.Forms.Label sm;
        private zdykj.UserControl UserCon;
        private System.Windows.Forms.DataGrid SortDataGird;
        private System.Windows.Forms.DataGridTableStyle dataGridTableStyle1;
        private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn1;
        private System.Windows.Forms.TextBox NameTb;
        private System.Windows.Forms.TextBox ExplainTb;
        private System.ComponentModel.Container components = null;
 
        public SortForm()
        {
            InitializeComponent();
        }
 
        ///<summary>
        ///清理所有正在使用的资源。
        ///</summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                   components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
 
        #region Windows 窗体设计器生成的代码
        ///<summary>
        ///设计器支持所需的方法 - 不要使用代码编辑器修改
        ///此方法的内容。
        ///</summary>
        private void InitializeComponent()
        {
            this.lm = new System.Windows.Forms.Label();
            this.sm = new System.Windows.Forms.Label();
            this.NameTb = new System.Windows.Forms.TextBox();
            this.ExplainTb = new System.Windows.Forms.TextBox();
            this.SortDataGird = new System.Windows.Forms.DataGrid();
            this.dataGridTableStyle1 = new System.Windows.Forms.DataGridTableStyle();
            this.dataGridTextBoxColumn1 = new System.Windows.Forms.DataGridTextBoxColumn();
            this.UserCon = new zdykj.UserControl();
            ((System.ComponentModel.ISupportInitialize)(this.SortDataGird)).BeginInit();
            this.SuspendLayout();
            //
            // lm
            //
            this.lm.Location = new System.Drawing.Point(8, 24);
            this.lm.Name = "lm";
            this.lm.Size = new System.Drawing.Size(86, 30);
            this.lm.TabIndex = 0;
            this.lm.Text = "类别名称:";
            //
            // sm
            //
            this.sm.Location = new System.Drawing.Point(8, 64);
            this.sm.Name = "sm";
            this.sm.Size = new System.Drawing.Size(86, 29);
            this.sm.TabIndex = 2;
            this.sm.Text = "说   明:";
            //
            // NameTb
            //
            this.NameTb.Location = new System.Drawing.Point(104, 24);
            this.NameTb.Name = "NameTb";
            this.NameTb.Size = new System.Drawing.Size(400, 25);
            this.NameTb.TabIndex = 4;
            this.NameTb.Text = "";
            //
            // ExplainTb
            //
            this.ExplainTb.Location = new System.Drawing.Point(104, 64);
            this.ExplainTb.Multiline = true;
            this.ExplainTb.Name = "ExplainTb";
            this.ExplainTb.Size = new System.Drawing.Size(400, 41);
            this.ExplainTb.TabIndex = 5;
            this.ExplainTb.Text = "";
            //
            // SortDataGird
            //
            this.SortDataGird.AlternatingBackColor = System.Drawing.Color.White;
            this.SortDataGird.BackColor = System.Drawing.Color.White;
            this.SortDataGird.BackgroundColor = System.Drawing.Color.Gainsboro;
            this.SortDataGird.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.SortDataGird.CaptionBackColor = System.Drawing.Color.Silver;
           this.SortDataGird.CaptionFont = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Bold);
            this.SortDataGird.CaptionForeColor = System.Drawing.Color.Black;
            this.SortDataGird.CaptionText = "类别所对应的产品";
            this.SortDataGird.DataMember = "";
            this.SortDataGird.FlatMode = true;
            this.SortDataGird.Font = new System.Drawing.Font("Courier New", 9F);
            this.SortDataGird.ForeColor = System.Drawing.Color.DarkSlateGray;
            this.SortDataGird.GridLineColor = System.Drawing.Color.DarkGray;
            this.SortDataGird.HeaderBackColor = System.Drawing.Color.DarkGreen;
            this.SortDataGird.HeaderFont = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Bold);
            this.SortDataGird.HeaderForeColor = System.Drawing.Color.White;
            this.SortDataGird.LinkColor = System.Drawing.Color.DarkGreen;
            this.SortDataGird.Location = new System.Drawing.Point(16, 120);
            this.SortDataGird.Name = "SortDataGird";
            this.SortDataGird.ParentRowsBackColor = System.Drawing.Color.Gainsboro;
            this.SortDataGird.ParentRowsForeColor = System.Drawing.Color.Black;
            this.SortDataGird.SelectionBackColor = System.Drawing.Color.DarkSeaGreen;
            this.SortDataGird.SelectionForeColor = System.Drawing.Color.Black;
            this.SortDataGird.Size = new System.Drawing.Size(488, 360);
            this.SortDataGird.TabIndex = 7;
            this.SortDataGird.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
                                                                                                   this.dataGridTableStyle1});
            //
            // dataGridTableStyle1
            //
            this.dataGridTableStyle1.DataGrid = this.SortDataGird;
            this.dataGridTableStyle1.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
                                                                                                              this.dataGridTextBoxColumn1});
            this.dataGridTableStyle1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGridTableStyle1.MappingName = "";
            //
            // dataGridTextBoxColumn1
            //
            this.dataGridTextBoxColumn1.Format = "";
            this.dataGridTextBoxColumn1.FormatInfo = null;
            this.dataGridTextBoxColumn1.HeaderText = "aaaa";
            this.dataGridTextBoxColumn1.MappingName = "";
            this.dataGridTextBoxColumn1.Width = 75;
            //
            // UserCon
            //
            this.UserCon.Location = new System.Drawing.Point(8, 504);
            this.UserCon.Name = "UserCon";
            this.UserCon.Size = new System.Drawing.Size(544, 52);
            this.UserCon.TabIndex = 8;
            this.UserCon.Load += new System.EventHandler(this.UserCon_Load);
            //
            // SortForm
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(8, 18);
            this.ClientSize = new System.Drawing.Size(568, 560);
            this.Controls.Add(this.UserCon);
            this.Controls.Add(this.SortDataGird);
            this.Controls.Add(this.ExplainTb);
            this.Controls.Add(this.NameTb);
            this.Controls.Add(this.sm);
            this.Controls.Add(this.lm);
            this.Name = "SortForm";
            this.Text = "类别";
            this.Load += new System.EventHandler(this.SortForm_Load);
            ((System.ComponentModel.ISupportInitialize)(this.SortDataGird)).EndInit();
            this.ResumeLayout(false);
 
        }
        #endregion
 
 
        //页面初始化
        private void SortForm_Load(object sender, System.EventArgs e)
        {
            try
            {
                string sqlCom = "select * from 类别";
                //得到返回的DataSet
                ds = sqldb.ds(sqlCom,"sort");
                //绑定“类别名称”文本框
                NameTb.DataBindings.Add("Text",ds.Tables["sort"],"类别名称");
                //绑定“说明”文本框
                ExplainTb.DataBindings.Add("Text",ds.Tables["sort"],"说明");
                //文本框显示为“1”
                UserCon.nuTb.Text = Convert.ToString(1);
                //获得总行数
                int count = ds.Tables["sort"].Rows.Count;
                //显示中行数
                UserCon.nulabel.Text = count.ToString();
                string liebieName = NameTb.Text.Trim();
                //在DataGrid中显示第一条的类别信息
                dataGridShou(liebieName);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 
        //自定义控件的页面初始化
        private void UserCon_Load(object sender, System.EventArgs e)
        {
            UserCon.zq +=new zdykj.UserControl.zuiqian(this.inzq);
            UserCon.xq += new zdykj.UserControl.xiangqian(this.inxq);
            UserCon.xh +=new zdykj.UserControl.xianghou(this.inxh);
            UserCon.zh +=new zdykj.UserControl.zuihou(this.inzh);
            UserCon.tl +=new zdykj.UserControl.total(this.intl);
            UserCon.nuTb.Text = Convert.ToString(1);
        }
       
        //实现“第一条”功能。
        public void inzq()
        {
            int z = 0;
            //文本框显示为“1”
            UserCon.nuTb.Text = (z +1).ToString();
            //绑定“类别名称”文本框(DataTable中第1行第1列)
            NameTb.Text = ds.Tables["sort"].Rows[z][1].ToString();
            //绑定“说明”文本框(DataTable中第1行第2列)
            ExplainTb.Text = ds.Tables["sort"].Rows[z][2].ToString();
            //获得“类别名称”(DataTable中第1行第1列)
            string liebieName = NameTb.Text.Trim();
            //在DataGrid中显示第1个类别信息
            dataGridShou(liebieName);
        }
       
        //实现“上一条”功能。
        public void inxq()
        {
            //判断当前条是否是第一条
            if(UserCon.nuTb.Text == Convert.ToString(1))
            {
                MessageBox.Show("已经到最前了");
            }
            else
            {
                //获得导航条中文本框中的文本
                string nuTb = UserCon.nuTb.Text;
                //如果文本框中是“5”,上一条就应该是“4”,在  DataTable中对应的就是“3”了,所以得减2.
                int z = Convert.ToInt32(nuTb)-2;
                //指向DataTable中第“3”行的数据
                this.BindingContext[ds,"sort"].Position = z;
                //在文本框中显示“4”
                UserCon.nuTb.Text = (z+1).ToString();
                //绑定“类别名称”文本框(DataTable中第“3”行第1列)
                NameTb.Text = ds.Tables["sort"].Rows[z][1].ToString();             
                //绑定“说明”文本框(DataTable中第“3”行第2列)
                ExplainTb.Text = ds.Tables["sort"].Rows[z][2].ToString();    
                //获得“类别名称”(DataTable中第“3”行第1列)
                string liebieName = NameTb.Text.Trim();
                //在DataGrid中显示第3个类别信息
                dataGridShou(liebieName);
            }
        }
 
        //实现“下一条”功能。
        public void inxh()
        {
                //判断是否是最后一条
                if(UserCon.nuTb.Text == this.BindingContext[ds,"sort"].Count.ToString())
                {
                   MessageBox.Show("已经到最后了");
                }
                else
                {  
                   string nuTb = UserCon.nuTb.Text;
                   //如果文本框中是“5”,下一条就应该是“6”,在  DataTable中对应还是“5”,所以z不用加减。
                   int z = Convert.ToInt32(nuTb);
                   this.BindingContext[ds,"sort"].Position = z;
                   NameTb.Text = ds.Tables["sort"].Rows[z][1].ToString();
                   ExplainTb.Text = ds.Tables["sort"].Rows[z][2].ToString();
                   UserCon.nuTb.Text = (z +1).ToString();
                   string liebieName = NameTb.Text.Trim();
                   dataGridShou(liebieName);
                }
        }
 
        //实现“最后一条”功能。
        public void inzh()
        {
            int z =this.BindingContext[ds,"sort"].Count-1;
            UserCon.nuTb.Text = (z +1).ToString();
            NameTb.Text = ds.Tables["sort"].Rows[z][1].ToString();
            ExplainTb.Text = ds.Tables["sort"].Rows[z][2].ToString();
            string liebieName = NameTb.Text.Trim();
            dataGridShou(liebieName);
        }
 
        //实现跳转功能。
        public void intl()
        {
            string nuTb = UserCon.nuTb.Text;
            //如果文本框中是“5”,指向DataTable中第“4”行的数据,所 以减1
            int z = Convert.ToInt32(nuTb)-1;
            this.BindingContext[ds,"sort"].Position = z;
            NameTb.Text = ds.Tables["sort"].Rows[z][1].ToString();
            ExplainTb.Text = ds.Tables["sort"].Rows[z][2].ToString();
            string liebieName = NameTb.Text.Trim();
            dataGridShou(liebieName);
        }
 
 
       
        //在SortDataGird中显示产品的信息,liebieName为类别名称
        private void dataGridShou(string liebieName)
        {
            string sqlCom = "SELECT distinct 产品.产品名称, 产品.单位数量, 产品.单价, case 产品.中止 when 0 then '否' when 1 then '是' end as 中止 FROM 类别,产品 where 产品.类别ID = (select 类别.类别ID from 类别 where 类别名称 = '" + liebieName + "')";
            ds = sqldb.ds(sqlCom,"lchanpin");
            SortDataGird.DataSource = ds.Tables["lchanpin"];
        }
    }
}
 
sqlDB.cs文件如下:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
 
namespace SellManage
{
    ///<summary>
    ///实现对数据库的访问
    ///</summary>
    public class sqlDB
    {
        DataSet datads = new DataSet();
        public sqlDB()
        {
        }
        private SqlConnection SqlCon;
       
        public void Open()
        {
            if (SqlCon == null)
            {
                string ConStr = "Data Source = .; Database = NorthwindCS; uid = sa; password =sa ";
                SqlCon = new SqlConnection(ConStr);           
            }              
            if(SqlCon.State == ConnectionState.Closed)
            {  
                try
                {
                   SqlCon.Open();
                }
                catch(Exception ex)
                {
                   MessageBox.Show(ex.Message);
                }
                finally
                {
                }
            }
        }
 
        public void Close()
        {
            if(SqlCon != null)
            {
                if(SqlCon.State == ConnectionState.Open)
                {
                   SqlCon.Close();
                }
            }
        }
 
        ///返回带表名的DataSet
        ///</summary>
        ///<param name="sqlCom">sql语句</param>
        ///<param name="DataTableName">DataSet的表名</param>
        ///<returns>返回带表名的DataSet</returns>
        public DataSet ds(string sqlCom , string DataTableName)
        {
            if(datads.Tables[DataTableName]!=null)
            {
                if(datads.Tables[DataTableName].Rows.Count>0)
                {
                   datads.Tables[DataTableName].Rows.Clear();
                }
            }
            try
            {
                Open();
                SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCom,SqlCon);
               
                sqlDa.Fill(datads,DataTableName);
                Close();
               
            }
        catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return datads;
        }
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,我会尽力回答你的问题。首先,ListView是ASP.NET Web Forms中的一个数据绑定控件,它可以用来呈现列表数据。而DataPager是用来实现数据分页的控件,可以和ListView一起使用来实现数据分页显示。 实现数据分页显示的步骤如下: 1. 在前端页面上添加ListView和DataPager控件,并设置它们的相关属性,比如ListView的数据源、布局方式、列样式等,DataPager的PageSize(每页显示的数据条数)和PagedControlID(分页控件绑定控件ID)等。 2. 在后端代码中,获取数据源并将其绑定到ListView控件上。 3. 在后端代码中,处理DataPager控件的PagePropertiesChanging事件,实现数据分页的逻辑,比如重新获取数据源并重新绑定到ListView控件上。 下面是一个简单的示例代码: 前端页面: ``` <asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1"> <LayoutTemplate> <table> <tr> <th>ID</th> <<th>Name</th> <th>Age</th> </tr> <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder> </table> </LayoutTemplate> <ItemTemplate> <tr> <td><%# Eval("ID") %></td> <td><%# Eval("Name") %></td> <td><%# Eval("Age") %></td> </tr> </ItemTemplate> </asp:ListView> <asp:DataPager ID="DataPager1" runat="server" PageSize="5" PagedControlID="ListView1"> <Fields> <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowPreviousPageButton="true" ShowNextPageButton="true" ShowLastPageButton="true" /> </Fields> </asp:DataPager> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" SelectCommand="SELECT * FROM MyTable"></asp:SqlDataSource> ``` 后端代码: ``` protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ListView1.DataBind(); } } protected void DataPager1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e) { DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false); ListView1.DataBind(); } ``` 以上代码中,ListView控件数据源使用了SqlDataSource控件,这里只是一个简单的示例,你也可以使用其他的数据控件。DataPager控件只添加了一个NextPreviousPagerField控件作为分页按钮,你也可以添加其他样式的控件,比如数字页码控件。在Page_Load事件中,第一次加载页面时会绑定数据到ListView控件上;在DataPager1_PagePropertiesChanging事件中,处理分页逻辑,重新获取数据源并重新绑定到ListView控件上。 希望这个简单的示例能够帮助你理解如何使用ListView和DataPager控件实现数据分页显示。如果你有任何问题或者需要进一步的帮助,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

orangapple

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值