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

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

事前準備

こちらまたはこちらの記事を参照してカード形式のデータベーステーブル参照アプリケーションを作成します。

UI

下図のUIを作成します。先に作成したアプリケーションに[更新]ボタンを追加します。

コード

下記のコードを記述します。
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 button7_Click(object sender, EventArgs e)
    {
      simpleProductBindingSource.EndEdit();
      simpleProductTableAdapter.Update(iPentecSandBoxDataSet.SimpleProduct);
    }
  }
}

解説

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

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。[前][次]ボタンを押して編集したいレコードを表示します。


テキストボックスを編集してレコードの値を変更します。変更ができたら[更新]ボタンを押します。


データベースに変更内容が反映されます。アプリケーションを再起動しレコードを表示すると変更後のレコードの値が表示されます。


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