c#Datagridview从数据库重新加载数据和向数据库提交更改

来源:互联网 发布:樱井知香磁力下载 编辑:程序博客网 时间:2024/05/29 16:30
//下面的完整代码示例提供的按钮用于从数据库重新加载数据和向数据库提交更改
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.");
        }
    }

}
0 0