using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;namespace winformdatagrid
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1; SqlDataAdapter adapter;
DataSet ds;
DataTable dtSource;
int PageCount;
int maxRec;
int pageSize;
int currentPage;
int recNo; DataTable dtTemp; //数据库新联接
private SqlConnection cn = new SqlConnection();
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button3; /// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null; public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
bind();
//
// 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.dataGrid1 = new System.Windows.Forms.DataGrid();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button3 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(0, 0);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(496, 273);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
this.dataGrid1.CurrentCellChanged += new System.EventHandler(this.mouseclick);
//
// button1
//
this.button1.Location = new System.Drawing.Point(240, 248);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "上一页";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(320, 248);
this.button2.Name = "button2";
this.button2.TabIndex = 2;
this.button2.Text = "下一页";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(136, 248);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 3;
this.textBox1.Text = "";
//
// button3
//
this.button3.Location = new System.Drawing.Point(400, 248);
this.button3.Name = "button3";
this.button3.TabIndex = 4;
this.button3.Text = "更新";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(496, 273);
this.Controls.Add(this.button3);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGrid1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void LoadPage()
{
int i;
int startRec;
int endRec;
//把数据源的数据复制到datatable中
dtTemp = dtSource.Clone(); if (currentPage == PageCount)
{
endRec = maxRec;
}
else
{
endRec = pageSize * currentPage;
}
startRec = recNo; //从源表拷贝行于临时表
for (i = startRec; i < endRec; i++)
{
dtTemp.ImportRow(dtSource.Rows[i]);
recNo += 1;
}
dataGrid1.DataSource = dtTemp;
//禁止新加一条记录
dtTemp.DefaultView.AllowNew=false;
DisplayPageInfo();
} private void DisplayPageInfo()
{
textBox1.Text = "Page " + currentPage.ToString() + "/ " + PageCount.ToString();
} private void fillpage()
{
pageSize = 10;
maxRec = dtSource.Rows.Count;
PageCount = maxRec / pageSize;
if ((maxRec % pageSize) > 0)
{
PageCount += 1;
} // 初始化
currentPage = 1;
recNo = 0; }
//绑定datagrid
public void bind()
{
OpenDatabase();
SqlConnection myConnection = cn;
ds = new DataSet();
adapter = new SqlDataAdapter("Select * from [ku1]", myConnection);
adapter.Fill(ds, "d1");
//绑定datagrid
dtSource = ds.Tables["d1"];
//dataGrid1.SetDataBinding(ds,"d1");
//关闭数据库连接
cn.Close();
//控制分页大小,总页数
fillpage();
//放于这里用于初始化页面
LoadPage();
//格式化样式
gsh(); }
//格式化表格样式
public void gsh()
{
DataGridTableStyle dgts=new DataGridTableStyle();
//隐藏最左边的一栏
dgts.RowHeadersVisible=false;
dgts.MappingName="d1";
DataGridTextBoxColumn dgtbc=new DataGridTextBoxColumn();
dgtbc.MappingName="khname";
dgtbc.HeaderText="公司名";
dgtbc.ReadOnly=true;
dgts.GridColumnStyles.Add(dgtbc); DataGridTextBoxColumn dgtbc2=new DataGridTextBoxColumn();
dgtbc2.MappingName="khDirector";
dgtbc2.HeaderText="负责人";
dgts.GridColumnStyles.Add(dgtbc2); dataGrid1.TableStyles.Add(dgts);
}
private void mouseclick(object sender,System.EventArgs e)
{
//显示点击的表格的内容
MessageBox.Show(dataGrid1[dataGrid1.CurrentCell].ToString()); }
//打开数据库
private void OpenDatabase()
{
if(cn.State.ToString().ToLower()=="open")
cn.Close();
cn.ConnectionString = "server=localhost;uid=sa;pwd=123a;database=mydatabase";
cn.Open();
}
private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
{
}
//下一页
private void button2_Click(object sender, System.EventArgs e)
{
if (pageSize == 0)
{
MessageBox.Show("没有数据!");
return;
} currentPage += 1;
if (currentPage > PageCount)
{
currentPage = PageCount;
//检查是否己是最后一页
if (recNo == maxRec)
{
MessageBox.Show("你己经在最后一页了!");
return;
}
}
LoadPage(); } private void button1_Click(object sender, System.EventArgs e)
{
if (currentPage == PageCount)
{
recNo = pageSize * (currentPage - 2);
}
//当前页-1
currentPage -= 1;
//检查是否己在第一页
if (currentPage < 1)
{
MessageBox.Show("你己经在第一页了!");
currentPage = 1;
return;
}
else
{
recNo = pageSize * (currentPage - 1);
}
LoadPage(); }
//这里点击更新
private void button3_Click(object sender, System.EventArgs e)
{
//修改的数据的状态在dtTemp所映出来.而在ds,dttable中的getchanges皆为空
if(dtTemp.GetChanges()!=null)
{
MessageBox.Show("dttemp有更新");
//这里应添加什么语句才能把修改或新加的记录更新到数据库中呢??
}
}
}
}
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;namespace winformdatagrid
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1; SqlDataAdapter adapter;
DataSet ds;
DataTable dtSource;
int PageCount;
int maxRec;
int pageSize;
int currentPage;
int recNo; DataTable dtTemp; //数据库新联接
private SqlConnection cn = new SqlConnection();
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button3; /// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null; public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
bind();
//
// 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.dataGrid1 = new System.Windows.Forms.DataGrid();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button3 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(0, 0);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(496, 273);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
this.dataGrid1.CurrentCellChanged += new System.EventHandler(this.mouseclick);
//
// button1
//
this.button1.Location = new System.Drawing.Point(240, 248);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "上一页";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(320, 248);
this.button2.Name = "button2";
this.button2.TabIndex = 2;
this.button2.Text = "下一页";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(136, 248);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 3;
this.textBox1.Text = "";
//
// button3
//
this.button3.Location = new System.Drawing.Point(400, 248);
this.button3.Name = "button3";
this.button3.TabIndex = 4;
this.button3.Text = "更新";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(496, 273);
this.Controls.Add(this.button3);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGrid1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void LoadPage()
{
int i;
int startRec;
int endRec;
//把数据源的数据复制到datatable中
dtTemp = dtSource.Clone(); if (currentPage == PageCount)
{
endRec = maxRec;
}
else
{
endRec = pageSize * currentPage;
}
startRec = recNo; //从源表拷贝行于临时表
for (i = startRec; i < endRec; i++)
{
dtTemp.ImportRow(dtSource.Rows[i]);
recNo += 1;
}
dataGrid1.DataSource = dtTemp;
//禁止新加一条记录
dtTemp.DefaultView.AllowNew=false;
DisplayPageInfo();
} private void DisplayPageInfo()
{
textBox1.Text = "Page " + currentPage.ToString() + "/ " + PageCount.ToString();
} private void fillpage()
{
pageSize = 10;
maxRec = dtSource.Rows.Count;
PageCount = maxRec / pageSize;
if ((maxRec % pageSize) > 0)
{
PageCount += 1;
} // 初始化
currentPage = 1;
recNo = 0; }
//绑定datagrid
public void bind()
{
OpenDatabase();
SqlConnection myConnection = cn;
ds = new DataSet();
adapter = new SqlDataAdapter("Select * from [ku1]", myConnection);
adapter.Fill(ds, "d1");
//绑定datagrid
dtSource = ds.Tables["d1"];
//dataGrid1.SetDataBinding(ds,"d1");
//关闭数据库连接
cn.Close();
//控制分页大小,总页数
fillpage();
//放于这里用于初始化页面
LoadPage();
//格式化样式
gsh(); }
//格式化表格样式
public void gsh()
{
DataGridTableStyle dgts=new DataGridTableStyle();
//隐藏最左边的一栏
dgts.RowHeadersVisible=false;
dgts.MappingName="d1";
DataGridTextBoxColumn dgtbc=new DataGridTextBoxColumn();
dgtbc.MappingName="khname";
dgtbc.HeaderText="公司名";
dgtbc.ReadOnly=true;
dgts.GridColumnStyles.Add(dgtbc); DataGridTextBoxColumn dgtbc2=new DataGridTextBoxColumn();
dgtbc2.MappingName="khDirector";
dgtbc2.HeaderText="负责人";
dgts.GridColumnStyles.Add(dgtbc2); dataGrid1.TableStyles.Add(dgts);
}
private void mouseclick(object sender,System.EventArgs e)
{
//显示点击的表格的内容
MessageBox.Show(dataGrid1[dataGrid1.CurrentCell].ToString()); }
//打开数据库
private void OpenDatabase()
{
if(cn.State.ToString().ToLower()=="open")
cn.Close();
cn.ConnectionString = "server=localhost;uid=sa;pwd=123a;database=mydatabase";
cn.Open();
}
private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
{
}
//下一页
private void button2_Click(object sender, System.EventArgs e)
{
if (pageSize == 0)
{
MessageBox.Show("没有数据!");
return;
} currentPage += 1;
if (currentPage > PageCount)
{
currentPage = PageCount;
//检查是否己是最后一页
if (recNo == maxRec)
{
MessageBox.Show("你己经在最后一页了!");
return;
}
}
LoadPage(); } private void button1_Click(object sender, System.EventArgs e)
{
if (currentPage == PageCount)
{
recNo = pageSize * (currentPage - 2);
}
//当前页-1
currentPage -= 1;
//检查是否己在第一页
if (currentPage < 1)
{
MessageBox.Show("你己经在第一页了!");
currentPage = 1;
return;
}
else
{
recNo = pageSize * (currentPage - 1);
}
LoadPage(); }
//这里点击更新
private void button3_Click(object sender, System.EventArgs e)
{
//修改的数据的状态在dtTemp所映出来.而在ds,dttable中的getchanges皆为空
if(dtTemp.GetChanges()!=null)
{
MessageBox.Show("dttemp有更新");
//这里应添加什么语句才能把修改或新加的记录更新到数据库中呢??
}
}
}
}
更新数据应该是adapter.update(ds)
public DataSet SelectSqlSrvRows(DataSet myDataSet,string myConnection,string mySelectQuery,string myTableName) {
SqlConnection myConn = new SqlConnection(myConnection);
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = new SqlCommand(mySelectQuery, myConn);
SqlCommandBuilder custCB = new SqlCommandBuilder(myDataAdapter); myConn.Open(); DataSet custDS = new DataSet();
myDataAdapter.Fill(custDS, "Customers"); //code to modify data in dataset here //Without the SqlCommandBuilder this line would fail
myDataAdapter.Update(custDS, "Customers"); myConn.Close(); return custDS;
}
这个datatable是在ds中把ds中的表复制过来的.对这个datatable的更改就仅对这个datatable中了.怎么反映在ds中?现在就是怎么把这个datatable的更改反映到数据库中?
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;namespace WindowsApplication10
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
SqlDataAdapter sda;
private System.Windows.Forms.Button button1;
DataSet ds; 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.dataGrid1 = new System.Windows.Forms.DataGrid();
this.button1 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(24, 16);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(168, 192);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
//
// button1
//
this.button1.Location = new System.Drawing.Point(144, 224);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click_1);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGrid1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} private void Form1_Load(object sender, System.EventArgs e)
{
try
{
string source=@"Integrated Security=SSPI;Initial Catalog=aa;Data Source=.";
string orders="select * from aa1";
SqlConnection conn=new SqlConnection(source);
sda=new SqlDataAdapter(orders,conn);
//关键
SqlCommandBuilder bld=new SqlCommandBuilder(sda);
ds=new DataSet();
sda.Fill(ds,"aa1");
this.dataGrid1.SetDataBinding(ds,"aa1");
//
}
catch(SqlException sq)
{
MessageBox.Show(sq.Message);
}
catch(Exception se)
{
MessageBox.Show(se.Message);
} }
private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
{
} private void button1_Click_1(object sender, System.EventArgs e)
{
if(ds.HasChanges())
{
this.sda.Update(ds,ds.Tables[0].TableName);
}
}
}}
private void button1_Click_1(object sender, System.EventArgs e)
{
if(ds.HasChanges())
{
this.sda.Update(ds,ds.Tables[0].TableName);
}
}
this.adapter.update(ds,ds.tables[0].tablename);
呢?
参考我的blog吧,上面有datagrid更新的详细介绍(包括程序和图片),就是不知道是否能解决你的问题。
blog.csdn.net/longge165
在上面留下你的邮箱,我可以把源码发给你。
你的blog我看了啊.没分页啊.没分页直接对ds操作就直接用this.adapter.update(ds,表名)这样就行.但是我不是直接对ds操作啊.因为对记灵修改后ds.getchanges()==null,一直是null,表明没有对ds有所操作...
da.Update(ds.Tables["tablename"].DefaultView.Table.Select("","",DataViewRowState.ModifiedCurrent))
================================================================
//把数据源的表结构复制到临时datatable中
dtTemp = dtSource.Clone();
然后有DataGrid绑定临时表进行修改
dataGrid1.DataSource = dtTemp;
//从源表拷贝行于临时表
for (i = startRec; i < endRec; i++)
{
dtTemp.ImportRow(dtSource.Rows[i]);
recNo += 1;
}//你在更新的时候可以调用
this.adapter.update(dtTemp);
因为表结构是一样的,
对于adapter.InsertCommand,
adapter.deleteCommand,
adapter.updateCommand
需要实例化写不同的Sql语句,
参考文章,
http://blog.csdn.net/zhzuo/archive/2004/08/06/67037.aspx
对于分页我觉得也可以实时取数据库的数据,而不是一次性都取出来,在并发操作的时候能尽量避免数据过时,
后台数据访问代码可以参考,
http://blog.csdn.net/zhzuo/archive/2004/09/22/113429.aspx
使用 Visual C# .NET 对 DataGrid Windows 控件执行分页
http://support.microsoft.com/default.aspx?scid=kb;zh-cn;307710