C# .NETASP(VS2019) DeskTopApplication [DataGridView DataSET] (2019-11)



// データセット版

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;


namespace WindowsFormsApp1 {
    public partial class Form1 : Form {

        public Form1() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) {


            OleDbConnection OleConn = new OleDbConnection();
            OleDbDataAdapter OleDA;
            DataSet dtSet = new DataSet("DAYDATA"); // テーブル名
                       
            OleConn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\database1.accdb"; // MDB名など
            OleDA = new OleDbDataAdapter("SELECT * FROM DAYDATA ORDER BY ID", OleConn);
            OleDA.Fill(dtSet, "DAYDATA");

            // DataGridViewにデータを表示
            dataGridView1.DataSource = dtSet.Tables[0];

            // 高さ変更
            dataGridView1.Columns[0].Width = 200;
            dataGridView1.Rows[0].Height = 50;

            // カラム名変更 DATAセットのSELECTの度に必要
            dataGridView1.Columns["DA"].HeaderText = "データ";
     	    // または dataGridView1.Columns[0].HeaderText = "社員番号";

        }

        private void button1_Click(object sender, EventArgs e) {

            // クリア
            dataGridView1.DataSource = null;
            dataGridView1.Rows.Clear();

            OleDbConnection OleConn = new OleDbConnection();
            OleDbDataAdapter OleDA;
            DataSet dtSet = new DataSet("DAYDATA");

            OleConn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\database1.accdb"; // MDB名など

            OleDA = new OleDbDataAdapter("SELECT * FROM DAYDATA ORDER BY ID DESC", OleConn);
            OleDA.Fill(dtSet, "DAYDATA");

            // DataGridViewにデータを表示
            dataGridView1.DataSource = dtSet.Tables[0];



        }
    }
}

戻る