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有更新");
         //这里应添加什么语句才能把修改或新加的记录更新到数据库中呢??
}
}
}
}

解决方案 »

  1.   

    绑定ds.Table(["d1"])
    更新数据应该是adapter.update(ds)
      

  2.   

    给你一个例子,将数据同步回去
    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;
     }
      

  3.   

    不符合啊.请仔细看下我的代码先回好嘛?有一个全局的ds,两个全局的datatable对数据的更改就反应在datatable中了.是用datatable.getchanges()!=null来检查的.
    这个datatable是在ds中把ds中的表复制过来的.对这个datatable的更改就仅对这个datatable中了.怎么反映在ds中?现在就是怎么把这个datatable的更改反映到数据库中?
      

  4.   

    是不是用WINDOWS用户进去无法UPDATA的啊
      

  5.   

    不是没什么连接.看下我那个按钮代码.是什么都没有写.想大家帮忙把里面写一点.就是把对datagrid的更新操作反映到数据库中.
      

  6.   

    看看我的程序,可以把结果更新到数据库
    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);
    }
    }
    }}
      

  7.   

    呵呵是不是很简单啊
    private void button1_Click_1(object sender, System.EventArgs e)
    {
    if(ds.HasChanges())
    {
    this.sda.Update(ds,ds.Tables[0].TableName);
    }
    }
      

  8.   

    对dataset的修改那肯定可以.但先把dataset所要显示的记录数复制到一个datatable中.然后把这个datatable绑定datagrid.那样.对datagrid的修该就是这个临时的datatable.而不是ds了.那有怎么可以用
    this.adapter.update(ds,ds.tables[0].tablename);
    呢?
      

  9.   

    为什么要把它先复制到另一张表中再修改呢?直接对dataset修改不也一样吗?只要用好事务处理就可以了。
    参考我的blog吧,上面有datagrid更新的详细介绍(包括程序和图片),就是不知道是否能解决你的问题。
    blog.csdn.net/longge165
    在上面留下你的邮箱,我可以把源码发给你。
      

  10.   

    就是因为要把datagrid分页才不对它直接修改啊.因为要分页.另一个datatable只是拷贝了ds中当前要显示页的记数.这样对这样的记录修改就会datatable修改而不是数据源ds的修改了.所以就遇到这样的问题..
    你的blog我看了啊.没分页啊.没分页直接对ds操作就直接用this.adapter.update(ds,表名)这样就行.但是我不是直接对ds操作啊.因为对记灵修改后ds.getchanges()==null,一直是null,表明没有对ds有所操作...
      

  11.   

    ds.Tables["tablename"].DefaultView.Table.Select("","",DataViewRowState.ModifiedCurrent)
      

  12.   

    少些了点东西--应该是这样的
    da.Update(ds.Tables["tablename"].DefaultView.Table.Select("","",DataViewRowState.ModifiedCurrent))
      

  13.   

    看来是用不了update的了.我用了个for循环把修改过的记录一条一条insert到库里了.
      

  14.   

    eprint自定义打印是一个页面套打工具.它直接在IE浏览器中可视化的设计各种复杂的打印模版,能够解决在IE浏览器中打印各种复杂的中国式报表及票据。
      

  15.   

    看了你上面的代码,大概理解如下:
    ================================================================
    //把数据源的表结构复制到临时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
      

  16.   

    谢谢:zhzuo(秋枫)能仔细看完我的代码..并给出对应合理的答案..