[ADO.NET]DataTableのデータをバインドする | Assertion Failed!

[ADO.NET]DataTableのデータをバインドする

DataTableのデータをバインドする


データベースからDataTableに取得したデータをそのままコントロールにバインド(結びつけ)するには、

各コントロールのDataSourceプロパティを使用する。


バインドが可能なコントロールの中には

  ・コンボボックス

  ・リストボックス

  ・DataGridView

などがある。


以下は、NorthWindデータベースからEmployeesテーブルを取得し、その中の

City列のデータをコンボボックスに表示する例。


string connectionString = "略";


using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("SELECT * FROM Employees", connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
  DataTable table = new DataTable();
  table.Locale = CultureInfo.InvariantCulture;
  try
  {
    adapter.Fill(table);
  }
  catch (SqlException)
  {
  }

  

  comboBox1.DataSource = table;

  comboBox1.DisplayMember = "City";
}


結果は以下のようになる。



Assertion Failed!