LoginSignup
3
13

More than 5 years have passed since last update.

C#のメモ帳 dataGridViewへのデータ設定(DB ⇒ SqlDataAdapter ⇒ DataTable ⇒ dataGridView)

Last updated at Posted at 2017-01-18

環境 

Visual Studo 2015, Win7

内容 

1. DBへの問い合わせ結果を DataTableに格納して、dataGridViewへ渡す方法
2. dataGridViewの細々とした表示の設定方法
3. 他のフォームのPublic変数を呼び出す方法

C# dataGridViewへのデータ設定
        private void 品目リスト表示()
        {

            //データをdataGridView品目リストにセットする--------------------------------------
            SqlConnection connection = new SqlConnection();
            SqlCommand command = new SqlCommand();
            //DataSet ds = new DataSet();        //データセットに格納する場合
            DataTable dt = new DataTable();

            // 接続文字列を設定します。
            Formメイン f = new Formメイン();     //他のフォームからPublic変数を呼び出し。
            connection.ConnectionString = f.DB接続文字列;
            f.Close();

            using (SqlDataAdapter adapter = new SqlDataAdapter())
            {
                command.Connection = connection;
                command.CommandText = "SELECT …それぞれ書いてね";

                adapter.SelectCommand = command;

                // SQLを実行し結果をdsの中に格納します。
         //【お勉強】Fill()でOpen/Closeを自動で行ってくれるので、記述不要。
         //     但し、Openしたら、Close要。
                //adapter.Fill(ds);             //データセット格納する場合
                adapter.Fill(dt);

            }

            dataGridView品目リスト.DataSource = dt;

            //dataGridView品目リストの設定----------------------------------------------------
            //ユーザの操作規制 ←これはFormのLoadへ持って行っても良い
            dataGridView品目リスト.ReadOnly = true;                      //読取専用
            dataGridView品目リスト.AllowUserToDeleteRows = false;        //行削除禁止
            dataGridView品目リスト.AllowUserToAddRows = false;           //行挿入禁止
            dataGridView品目リスト.AllowUserToResizeRows = false;        //行の高さ変更禁止              
            dataGridView品目リスト.RowHeadersVisible = false;            //行ヘッダーを非表示にする
            dataGridView品目リスト.MultiSelect = false;                  //ル、行、列が複数選択禁止
            dataGridView品目リスト.SelectionMode = DataGridViewSelectionMode.FullRowSelect;       //セルを選択すると行全体が選択されるようにする

            //ヘッダー名変更
            dataGridView品目リスト.Columns[0].HeaderText = "品目コード";
            dataGridView品目リスト.Columns[1].HeaderText = "品目名";
            dataGridView品目リスト.Columns[2].HeaderText = "包装形態";
            //カラム幅設定
            dataGridView品目リスト.Columns[0].Width = 60;
            dataGridView品目リスト.Columns[1].Width = 200;
            dataGridView品目リスト.Columns[2].Width = 60;

        }

参考にさせて頂いたページ 感謝!

猫のきままなC#日記
VB全ては時の中に…
 

3
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
13