準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にボタン (button2) を配置します。
- フォーム (Form1) にテキストボックス (textBox1) を配置します。
- フォーム (Form1) にテキストボックス (textBox2) を配置します。
- フォーム (Form1) にバインディングソース (bindingSource1) を配置します。
サンプルコード (C#)
using System.Data;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var ds = new DataSet();
var dt = ds.Tables.Add("Computer");
dt.Columns.Add("メーカー");
dt.Columns.Add("パソコン名");
dt.Rows.Add(new string[] { "NEC", "ValueStar" });
dt.Rows.Add(new string[] { "SONY", "VAIO" });
dt.Rows.Add(new string[] { "DELL", "Precision" });
bindingSource1.DataSource = ds;
bindingSource1.DataMember = "Computer";
textBox1.DataBindings.Add("Text", bindingSource1, "メーカー");
textBox2.DataBindings.Add("Text", bindingSource1, "パソコン名");
}
private void button1_Click(object sender, EventArgs e)
{
bindingSource1.MovePrevious();
}
private void button2_Click(object sender, EventArgs e)
{
bindingSource1.MoveNext();
}
}
}
解説
テキストボックスにバインディングソースを設定しています。バインディングソースには事前に作成したデータセットが割り当てられています。
button1 をクリックすると、テキストボックスの内容が前のデータに移動します。button2 をクリックすると次のデータに移動します。
結果
動作確認環境
Visual Studio 2022 Professional (.NET8 C#12)
ログ
初版:2016.05.14 Visual Studio 2015 Professional (C# 6.0)
