您的位置:首页 > 编程语言 > C#

C#中DataGrid分页,修改,更新,删除功能的实现

2007-05-10 17:45 951 查看
第一次写博客,不知道写写什么好,就写写自己最近做的东西把。

a,实现分页的存储过程:首先新件一表: UserInfo,在这里我把DataGrid 的 PerPage=10

CREATE PROCEDURE GetUserPage
(
@UserNum int, --设置每页显示的记录数
@StartNO int, --当前页的页码
@@TotalCount int output, --所有记录数
@@RealNum int output --每页的实际记录数
)
AS
declare @PreRecCount varchar( 10 ) --当前页之前的所有页的记录数
declare @CurRecCount varchar( 10 ) --<=当前页的所有记录数
select @@TotalCount = COUNT(*) FROM UserInfo
if @@TotalCount > ( @StartNO + 1 ) * @UserNum
set @@RealNum = @UserNum
else
set @@RealNum = @@TotalCount - @StartNO * @UserNum
set @CurRecCount = CAST( @StartNO * @UserNum + @@RealNum as varchar( 10 ) )
if @StartNO = 0 -- 第一页为 0
exec( 'SELECT TOP ' + @CurRecCount + ' * FROM UserInfo ORDER BY ID ASC' )
else
begin
set @PreRecCount = CAST( @StartNO * @UserNum as varchar(50 ) )
exec( 'SELECT TOP 10 * FROM UserInfo WHERE ID NOT IN ' --使用 'NOT IN '方法
+ '(SELECT TOP ' + @PreRecCount + ' ID FROM UserInfo ORDER BY ID ASC) '
+ 'ORDER BY ID ASC'
)
END
GO

相关代码:

1.首先实现与数据库的连接:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="server=.;uid=sa;pwd=11;DataBase=DataGrid"/>
</appSettings>
</configuration>

注:这是比较简单的数据库连接方法,也是最基本的,可以选用适合自己的数据库连接方法

2.具体功能的实现:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace DataGridWin
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid DataGrid;
private System.Windows.Forms.Button btnOK;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
private SqlCommandBuilder sql_cb;
public static readonly string connstr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString();
public SqlConnection conn;
public SqlDataAdapter adapter;
private System.Windows.Forms.Button btnExit;
public DataSet ds;
public int nCurPageNum = 0;
public const int perPage = 10;
public int nTotalCount;
//publicint nRealNum;
private System.Windows.Forms.Label lblPageInfo;
private System.Windows.Forms.Button btnPrevious;
private System.Windows.Forms.Button btnNext;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnUpdate;
private System.Windows.Forms.Button btnDel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtData;
private System.Windows.Forms.Button btnObj;
public int nTotalPage;
public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 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.DataGrid = new System.Windows.Forms.DataGrid();
this.btnOK = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.lblPageInfo = new System.Windows.Forms.Label();
this.btnPrevious = new System.Windows.Forms.Button();
this.btnNext = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.btnUpdate = new System.Windows.Forms.Button();
this.btnDel = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.txtData = new System.Windows.Forms.TextBox();
this.btnObj = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.DataGrid)).BeginInit();
this.SuspendLayout();
//
// DataGrid
//
this.DataGrid.AllowDrop = true;
this.DataGrid.AlternatingBackColor = System.Drawing.Color.Silver;
this.DataGrid.BackColor = System.Drawing.Color.White;
this.DataGrid.CaptionBackColor = System.Drawing.Color.Maroon;
this.DataGrid.CaptionFont = new System.Drawing.Font("Tahoma", 8F);
this.DataGrid.CaptionForeColor = System.Drawing.Color.White;
this.DataGrid.DataMember = "";
this.DataGrid.Font = new System.Drawing.Font("Tahoma", 8F);
this.DataGrid.ForeColor = System.Drawing.Color.Black;
this.DataGrid.GridLineColor = System.Drawing.Color.Silver;
this.DataGrid.HeaderBackColor = System.Drawing.Color.Silver;
this.DataGrid.HeaderFont = new System.Drawing.Font("Tahoma", 8F);
this.DataGrid.HeaderForeColor = System.Drawing.Color.Black;
this.DataGrid.LinkColor = System.Drawing.Color.Maroon;
this.DataGrid.Location = new System.Drawing.Point(80, 8);
this.DataGrid.Name = "DataGrid";
this.DataGrid.ParentRowsBackColor = System.Drawing.Color.Silver;
this.DataGrid.ParentRowsForeColor = System.Drawing.Color.Black;
this.DataGrid.SelectionBackColor = System.Drawing.Color.Maroon;
this.DataGrid.SelectionForeColor = System.Drawing.Color.White;
this.DataGrid.Size = new System.Drawing.Size(360, 248);
this.DataGrid.TabIndex = 0;
//
// btnOK
//
this.btnOK.Location = new System.Drawing.Point(88, 304);
this.btnOK.Name = "btnOK";
this.btnOK.TabIndex = 1;
this.btnOK.Text = "显 示";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnExit
//
this.btnExit.Location = new System.Drawing.Point(176, 304);
this.btnExit.Name = "btnExit";
this.btnExit.TabIndex = 2;
this.btnExit.Text = "退出";
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// lblPageInfo
//
this.lblPageInfo.Location = new System.Drawing.Point(296, 312);
this.lblPageInfo.Name = "lblPageInfo";
this.lblPageInfo.Size = new System.Drawing.Size(112, 23);
this.lblPageInfo.TabIndex = 3;
//
// btnPrevious
//
this.btnPrevious.Location = new System.Drawing.Point(88, 360);
this.btnPrevious.Name = "btnPrevious";
this.btnPrevious.TabIndex = 4;
this.btnPrevious.Text = "上一页";
this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click);
//
// btnNext
//
this.btnNext.Location = new System.Drawing.Point(176, 360);
this.btnNext.Name = "btnNext";
this.btnNext.TabIndex = 5;
this.btnNext.Text = "下一页";
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(272, 360);
this.btnAdd.Name = "btnAdd";
this.btnAdd.TabIndex = 6;
this.btnAdd.Text = "新 建";
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnUpdate
//
this.btnUpdate.Location = new System.Drawing.Point(88, 408);
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.TabIndex = 7;
this.btnUpdate.Text = "修改/更新";
this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
//
// btnDel
//
this.btnDel.Location = new System.Drawing.Point(176, 408);
this.btnDel.Name = "btnDel";
this.btnDel.TabIndex = 8;
this.btnDel.Text = "删 除";
this.btnDel.Click += new System.EventHandler(this.btnDel_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(264, 408);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(64, 23);
this.label1.TabIndex = 9;
this.label1.Text = "跳 转 到:";
//
// txtData
//
this.txtData.Location = new System.Drawing.Point(320, 408);
this.txtData.Name = "txtData";
this.txtData.Size = new System.Drawing.Size(48, 21);
this.txtData.TabIndex = 10;
this.txtData.Text = "";
//
// btnObj
//
this.btnObj.Location = new System.Drawing.Point(368, 408);
this.btnObj.Name = "btnObj";
this.btnObj.TabIndex = 11;
this.btnObj.Text = "跳 转";
this.btnObj.Visible = false;
this.btnObj.Click += new System.EventHandler(this.btnObj_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(584, 461);
this.Controls.Add(this.btnObj);
this.Controls.Add(this.txtData);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnDel);
this.Controls.Add(this.btnUpdate);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnNext);
this.Controls.Add(this.btnPrevious);
this.Controls.Add(this.lblPageInfo);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.DataGrid);
this.Name = "Form1";
this.Text = "DataGrid";
((System.ComponentModel.ISupportInitialize)(this.DataGrid)).EndInit();
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1()); --设置启动页Form1
}
private void Data()
{
try
{
string sql = "select * from UserInfo"; -- 在这里用存储过程比较好,为了简单就使用了SQl语句
conn = new SqlConnection(connstr);
conn.Open();
adapter = new SqlDataAdapter(sql,conn);
ds = new DataSet();
adapter.Fill(ds,nCurPageNum,perPage,"UserInfo");
sql_cb = new SqlCommandBuilder(adapter);
DataGrid.SetDataBinding(ds,"UserInfo");
}
catch(Exception error)
{
throw new Exception(error.Message,error);
}
finally
{
conn.Close();
}
}
private void btnOK_Click(object sender, System.EventArgs e)
{
Data();
btnObj.Visible = true;
}

private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close(); --关闭窗口
}

private void btnPrevious_Click(object sender, System.EventArgs e)
{
btnOK.Enabled = false;
if(nCurPageNum==0)
{
MessageBox.Show("该页为第一页");
}
else
{
nCurPageNum--;
ds.Tables["UserInfo"].Rows.Clear();
DataGridDataBind();
}
}

private void btnNext_Click(object sender, System.EventArgs e)
{
btnOK.Enabled = false;
nCurPageNum++;
ds.Tables["UserInfo"].Rows.Clear();
DataGridDataBind();
}
private void GetUserData()
{
conn = new SqlConnection(connstr);
conn.Open();
adapter = new SqlDataAdapter("GetUserPage",conn);
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.Parameters.Add("@UserNum",perPage);
adapter.SelectCommand.Parameters.Add("@StartNO",nCurPageNum);
SqlParameter sqlPar = adapter.SelectCommand.Parameters.Add ( "@@TotalCount", SqlDbType.Int );
sqlPar.Direction = ParameterDirection.Output;

sqlPar = adapter.SelectCommand.Parameters.Add ( "@@RealNum", SqlDbType.Int );
sqlPar.Direction = ParameterDirection.Output;

ds = new DataSet();
adapter.Fill(ds,"UserInfo");
nTotalCount = Convert.ToInt32(adapter.SelectCommand.Parameters["@@TotalCount"].Value.ToString());
//nRealNum = Convert.ToInt32(adapter.SelectCommand.Parameters["@@RealNum"].Value.ToString());
adapter.SelectCommand.Dispose();
nTotalPage = nTotalCount - nTotalCount % perPage;
nTotalPage = nTotalPage/perPage;
lblPageInfo.Text = string.Format("{0} of {1} pages", nCurPageNum, nTotalPage );
if(nCurPageNum+1 >nTotalPage)
{
btnNext.Enabled = false;
}
else
{
btnNext.Enabled = true;
}
if(nCurPageNum == 0)
{
btnPrevious.Enabled = false;
}
else
{
btnPrevious.Enabled = true;
}
}
private void DataGridDataBind()
{
GetUserData();
DataGrid.SetDataBinding(ds,"UserInfo");
}

private void btnAdd_Click(object sender, System.EventArgs e)
{
btnOK.Enabled = true;
DataGrid.CurrentCell = new DataGridCell(ds.Tables["UserInfo"].Rows.Count,1);
}

private void btnUpdate_Click(object sender, System.EventArgs e)
{
btnOK.Enabled = true;
adapter.Update(ds,"UserInfo");
ds.Tables["UserInfo"].AcceptChanges();
}

private void btnDel_Click(object sender, System.EventArgs e)
{
btnOK.Enabled = true;
Data();
ds.Tables["UserInfo"].DefaultView.AllowDelete = true;
int Index = DataGrid.CurrentRowIndex;
ds.Tables["UserInfo"].DefaultView.Delete(Index);
adapter.Update(ds,"UserInfo");
ds.Tables["UserInfo"].AcceptChanges();
}

private void btnObj_Click(object sender, System.EventArgs e)
{
int Data = Convert.ToInt32(txtData.Text.ToString());
btnOK.Enabled = false;
nCurPageNum=Data;
ds.Tables["UserInfo"].Rows.Clear();
DataGridDataBind();
if(nCurPageNum>nTotalPage)
{
MessageBox.Show("输入的值超出范围!");
}
}
}
}

* 上面功能简单,主要实现了在winform中对DataGrid控件基本的添加,修改,更新,删除,分页的功能对于初学者应该能看的懂。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐