c#之datagridview控制元件_用於從資料庫重新載入資料和向資料庫提交更改

wisdomone1發表於2011-08-26

//下面的完整程式碼示例提供的按鈕用於從資料庫重新載入資料和向資料庫提交更改
using System;
using System.Data;
using System.Data.SqlClient;//sqlclient是與sqlserver互動的名稱空間,若為oracle,則是system.data.oracleclient;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
    private DataGridView dataGridView1 = new DataGridView();//系統自動生成
    private BindingSource bindingSource1 = new BindingSource();//bindingsource元件用於管理控制元件和資料來源繫結工作,簡化這個繫結管理
    private SqlDataAdapter dataAdapter = new SqlDataAdapter();//sqldataadapter用於把加工的命令到資料集合上(由command->datatable或者command->dataset)
    private Button reloadButton = new Button();
    private Button submitButton = new Button();

    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new Form1());//application類
    }

    // Initialize the form.
    public Form1()
    {
        dataGridView1.Dock = DockStyle.Fill;

        reloadButton.Text = "reload";
        submitButton.Text = "submit";
         //reloadbuttion.click+=new system.eventhandler(要訂閱的事件名)
        reloadButton.Click += new System.EventHandler(reloadButton_Click);//為過載按鈕訂閱事件reloadbutton_click
        submitButton.Click += new System.EventHandler(submitButton_Click);

          //皮膚控制元件,用於包含其它子控制元件,類似於容器控制元件
        FlowLayoutPanel panel = new FlowLayoutPanel();
        panel.Dock = DockStyle.Top;
        panel.AutoSize = true;

         //皮膚控制元件包含過載及提交按鈕
         //panel1.controls.addrange(new control[] {控制元件名稱})
        panel.Controls.AddRange(new Control[] { reloadButton, submitButton });

         //this表示form窗體
         //將上述的皮膚及datagridview新增到當前窗體中
        this.Controls.AddRange(new Control[] { dataGridView1, panel });
        this.Load += new System.EventHandler(Form1_Load);
        this.Text = "DataGridView databinding and updating demo";
    }

       //窗體載入事件
    private void Form1_Load(object sender, System.EventArgs e)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
         //繫結datagridview的資料來源為bindingsource元件配置的資料來源
        dataGridView1.DataSource = bindingSource1;
          //呼叫getdata方法顯示sql執行結果
        GetData("select * from Customers");
    }

    private void reloadButton_Click(object sender, System.EventArgs e)
    {
        // Reload the data from the database.
        GetData(dataAdapter.SelectCommand.CommandText);
    }

    private void submitButton_Click(object sender, System.EventArgs e)
    {
        // Update the database with the user's changes.
        dataAdapter.Update((DataTable)bindingSource1.DataSource);
    }

        //getdata方法的實現體
    private void GetData(string selectCommand) //方法引數為執行的sql
    {
        try
        {
            // Specify a connection string. Replace the given value with a
            // valid connection string for a Northwind SQL Server sample
            // database accessible to your system.
            //連線的資料庫資訊
            String connectionString =
                "Integrated Security=SSPI;Persist Security Info=False;" +
                "Initial Catalog=Northwind;Data Source=localhost";

            // Create a new data adapter based on the specified query.
             //sqldataadapter,建構函式為執行命令,連線字串
            dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand. These are used to
            // update the database.
                  //sqlcommandbuiler
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            // Populate a new data table and bind it to the BindingSource.
                 //datatable表(記憶體表)
            DataTable table = new DataTable();
               //datatable表的文化配置
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
              //透過sqldataadapter的fill方法把sql執行結果裝配至datatable記憶體表中
            dataAdapter.Fill(table);
               //這下datatable記憶體表有資料了,就讓bindingsource等於它
            bindingSource1.DataSource = table;

            // Resize the DataGridView columns to fit the newly loaded content.
                  //重形成大小datagridview以適應過載後的變化
            dataGridView1.AutoResizeColumns(
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        }
        catch (SqlException)
        {
            MessageBox.Show("To run this example, replace the value of the " +
                "connectionString variable with a connection string that is " +
                "valid for your system.");
        }
    }

}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-705884/,如需轉載,請註明出處,否則將追究法律責任。

相關文章