カード形式のデータベースアプリケーションにレコードの追加機能を実装する - BindingSourceを利用したレコードの追加 - C#

こちらの記事で作成した、カード形式のデータベースアプリケーションにレコードの追加機能を追加する手順を紹介します。BindingSourceを用いたアプリケーションでのレコード追加方法です。

事前準備

こちらの記事で作成した、カード形式のデータベースアプリケーションを作成します。

UI

下図のUIを準備します。先のこちらの記事で作成したアプリケーションにボタンを2つ(button4,button5)追加します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SimpleCardApp
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      // TODO: このコード行はデータを 'iPentecSandBoxDataSet.SimpleProduct' テーブルに読み込みます。
        //必要に応じて移動、または削除をしてください。
      this.simpleProductTableAdapter.Fill(this.iPentecSandBoxDataSet.SimpleProduct);
    }

    private void button1_Click(object sender, EventArgs e)
    {
      simpleProductBindingSource.MovePrevious();
    }

    private void button2_Click(object sender, EventArgs e)
    {
      simpleProductBindingSource.MoveNext();
    }

    private void button4_Click(object sender, EventArgs e)
    {
      simpleProductBindingSource.AddNew();
    }

    private void button5_Click(object sender, EventArgs e)
    {
      simpleProductBindingSource.EndEdit();
      simpleProductTableAdapter.Update(iPentecSandBoxDataSet.SimpleProduct);
    }
  }
}

解説

private void button4_Click(object sender, EventArgs e)
{
  simpleProductBindingSource.AddNew();
}
button4のクリックでは、BindingSourceコンポーネントのAddNew()メソッドを呼び出しBindingSourceに新しいレコードを挿入します。

private void button5_Click(object sender, EventArgs e)
{
  simpleProductBindingSource.EndEdit();
  simpleProductTableAdapter.Update(iPentecSandBoxDataSet.SimpleProduct);
}
button5のクリックではBindingSourceコンポーネントのEndEdit()メソッドを呼び出し編集を確定します。確定後TableAdapterコンポーネントのUpdateメソッドを呼び出しデータソース(データベース)を更新します。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


button4をクリックします。新しいレコードが追加されます。IDのフィールドには-1が仮置きで入力されています。


他のフィールドを入力します。入力後button5をクリックします。


データベースが更新されます。データベース側でIDが採番され、確定したIDがテキストボックスに反映されています。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-07
作成日: 2012-10-25
iPentec all rights reserverd.