http://lucky_elove.www1.dotnetplayground.com/ShowDetail.aspx?id=8ADE535F-AD40-4DE3-A962-A64B4FAF12C4

解决方案 »

  1.   

    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Data.SqlClient;namespace CustomerEditor
    {
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.MainMenu mainMenu;
    private System.Windows.Forms.MenuItem menuData;
    private System.Windows.Forms.MenuItem menuDataConnect;
    private SqlConnection _connection;
    private System.Windows.Forms.MenuItem menuDataLoad;
    private System.Windows.Forms.DataGrid dataGridCustomers;
    private System.Windows.Forms.MenuItem menuDataSaveChanges; /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null; public Form1()
    {
    //
    // Required for Windows Form Designer support
    //
    InitializeComponent(); //
    // TODO: Add any constructor code after InitializeComponent call
    //
    } /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    Disconnect(); if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    this.mainMenu = new System.Windows.Forms.MainMenu();
    this.menuData = new System.Windows.Forms.MenuItem();
    this.menuDataConnect = new System.Windows.Forms.MenuItem();
    this.menuDataLoad = new System.Windows.Forms.MenuItem();
    this.menuDataSaveChanges = new System.Windows.Forms.MenuItem();
    this.dataGridCustomers = new System.Windows.Forms.DataGrid();
    ((System.ComponentModel.ISupportInitialize)(this.dataGridCustomers)).BeginInit();
    this.SuspendLayout();
    // 
    // mainMenu
    // 
    this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
     this.menuData});
    // 
    // menuData
    // 
    this.menuData.Index = 0;
    this.menuData.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
     this.menuDataConnect,
     this.menuDataLoad,
     this.menuDataSaveChanges});
    this.menuData.Text = "&Data";
    // 
    // menuDataConnect
    // 
    this.menuDataConnect.Index = 0;
    this.menuDataConnect.Text = "连接(&C)";
    this.menuDataConnect.Click += new System.EventHandler(this.menuDataConnect_Click);
    // 
    // menuDataLoad
    // 
    this.menuDataLoad.Index = 1;
    this.menuDataLoad.Text = "数据加载(&L)";
    this.menuDataLoad.Click += new System.EventHandler(this.menuDataLoad_Click);
    // 
    // menuDataSaveChanges
    // 
    this.menuDataSaveChanges.Index = 2;
    this.menuDataSaveChanges.Text = "保存变化(&S)";
    this.menuDataSaveChanges.Click += new System.EventHandler(this.menuDataSaveChanges_Click);
    // 
    // dataGridCustomers
    // 
    this.dataGridCustomers.DataMember = "";
    this.dataGridCustomers.Dock = System.Windows.Forms.DockStyle.Fill;
    this.dataGridCustomers.HeaderForeColor = System.Drawing.SystemColors.ControlText;
    this.dataGridCustomers.Name = "dataGridCustomers";
    this.dataGridCustomers.Size = new System.Drawing.Size(373, 315);
    this.dataGridCustomers.TabIndex = 0;
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(373, 315);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
      this.dataGridCustomers});
    this.Menu = this.mainMenu;
    this.Name = "Form1";
    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
    this.Text = "Form1";
    this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    this.Load += new System.EventHandler(this.Form1_Load);
    ((System.ComponentModel.ISupportInitialize)(this.dataGridCustomers)).EndInit();
    this.ResumeLayout(false); }
    #endregion /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    } public void Connect()
    {
    string connectionString = "";
    connectionString = "Data Source=localhost;Initial Catalog=Northwind " + 
    ";User ID=sa;Password=";
    try
    { SqlConnection newConnection = new SqlConnection(connectionString); newConnection.Open(); Connection = newConnection;
    }
    catch(Exception ex)
    {
    HandleException("无法连接指定的服务器", ex);
    }
    } public void HandleException(string message, Exception ex)
    {
    MessageBox.Show(this, string.Format("{0}\n{1}:{2}",
    message, ex.GetType().ToString(), ex.Message));
    } public SqlConnection Connection
    {
    get
    {
    return _connection;
    }
    set
    {
    Disconnect(); _connection = value;
    }
    } public void Disconnect()
    {
    if(_connection != null)
    {
    if(_connection.State != ConnectionState.Closed)
    _connection.Close(); _connection = null;
    }
    } private void menuDataConnect_Click(object sender, System.EventArgs e)
    {
    Connect();
    } private void Form1_Load(object sender, System.EventArgs e)
    { } private void menuDataLoad_Click(object sender, System.EventArgs e)
    {
    LoadData();
    }
      

  2.   

    private void LoadData()
    {
    //是否已有连接
    if(_connection == null)
    {
    MessageBox.Show(this, "请先建立连接。");
    return;
    } //setup
    try
    {
    //建立并且填充tables
    DataTable datatable = CreateAndFill("Customers");
    //显示这个datatable
    dataGridCustomers.DataSource = datatable;
    //dataGridCustomers.DataMember = datatable;
    }
    catch(Exception ex)
    {
    HandleException("无法加载指定数据。",ex);
    } }
    private DataTable CreateAndFill(string tableName)
    {
    DataSet dataset;
    SqlCommand command = new SqlCommand("select * from Customers", _connection);
    SqlDataAdapter adapter = new SqlDataAdapter(command);
    dataset = new DataSet();
    try
    {
    adapter.Fill(dataset);
    }
    catch(Exception ex)
    {
    HandleException("无法加载指定数据。",ex);
    }
    finally
    {
    //释放资源。
    if (adapter != null)
    adapter.Dispose();
    if (command != null)
    command.Dispose();
    } DataTable table = new DataTable(tableName);
    table = dataset.Tables[0];
    dataset.Dispose();
    return table;
    } private void menuDataSaveChanges_Click(object sender, System.EventArgs e)
    {
    //SaveChanges();
    SaveChanges1();
    } private void SaveChanges()
    {
    //是否已有连接
    if(_connection == null)
    {
    MessageBox.Show(this, "请先建立连接。");
    return;
    } //取得dataset
    DataTable table = (DataTable)dataGridCustomers.DataSource;
    if (table == null)
    {
    MessageBox.Show("请先加载数据");
    return;
    } //建立修改
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = new SqlCommand("select * from Customers", _connection);
    try
    {
    SqlCommandBuilder commandbuilder = new SqlCommandBuilder(adapter); //_connection.Open(); //此处不能open,否则出错。 adapter.Fill(table); adapter.Update(table);
    table.AcceptChanges(); MessageBox.Show("修改成功");
    }
    catch(Exception ex)
    {
    Exception ConnectionFailure = new Exception(ex.GetType().ToString() + ex.Message);
    throw ConnectionFailure;
    }
    finally
    {
    if (adapter != null)
    adapter.Dispose();
    }
    } private void SaveChanges1()
    {
    //试验重新打开联接是否有影响。结果为可以保存,但table有影响,每运行一次记录数量加一次实际数量,造成显示错误,必须重新取table。
    Connect(); //取得dataset
    DataTable table = (DataTable)dataGridCustomers.DataSource;
    if (table == null)
    {
    MessageBox.Show("请先加载数据");
    return;
    } //建立修改
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = new SqlCommand("select * from Customers", _connection);
    try
    {
    SqlCommandBuilder commandbuilder = new SqlCommandBuilder(adapter); //_connection.Open(); //此处不能open,否则出错。 adapter.Fill(table); adapter.Update(table);
    table.AcceptChanges(); MessageBox.Show("修改成功");
    }
    catch(Exception ex)
    {
    Exception ConnectionFailure = new Exception(ex.GetType().ToString() + ex.Message);
    throw ConnectionFailure;
    }
    finally
    {
    if (adapter != null)
    adapter.Dispose();
    }
    } }
    }代码较长,只能分二次贴上。