datagridview连接着数据库中的表

解决方案 »

  1.   


    public partial class Form1 : Form
        {
            private OleDbConnection connection = null;
            private OleDbCommand selectCommand = null;
            private OleDbDataAdapter dataAdapter = null;
            private string connectionString = 
                @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\DB\Customers.mdb;Persist Security Info=True";        public Form1()
            {
                InitializeComponent();
            }        private void Form1_Load(object sender, EventArgs e)
            {
                connection = new OleDbConnection(connectionString);
                selectCommand = connection.CreateCommand();
                selectCommand.CommandText = "SELECT CustomerID, CompanyName, ContactName, Address, Phone FROM Customers";
                dataAdapter = new OleDbDataAdapter();
                dataAdapter.SelectCommand = selectCommand;
                DataTable data = new DataTable();
                dataAdapter.Fill(data);
                this.dataGridView1.DataSource = data;            OleDbCommandBuilder builder = new OleDbCommandBuilder(dataAdapter);
                dataAdapter.UpdateCommand = builder.GetUpdateCommand();
                dataAdapter.InsertCommand = builder.GetInsertCommand();
                dataAdapter.DeleteCommand = builder.GetDeleteCommand();
            }        private void button1_Click(object sender, EventArgs e)
            {
                DataTable data = (DataTable)this.dataGridView1.DataSource;
                DataTable changedData = data.GetChanges();            if (changedData != null)
                {
                    dataAdapter.Update(changedData);
                    data.AcceptChanges();
                }
            }
        }