C# コードで SQL Server にあるテーブルに接続して、取得した結果(SqlDataReader)を DataTable に読み込む例です。データベースへの接続には、SqlDataSource インスタンスを生成して接続文字列を予め設定しています。
ASPX:
<asp:SqlDataSource
ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>">
</asp:SqlDataSource>
コードビハインド:
// 接続文字列を指定してデータベースを指定
SqlConnection conn =
new SqlConnection(this.SqlDataSource1.ConnectionString);
// 接続を開く
conn.Open();
// テーブルを取得する
string sqlQuery = "SELECT * FROM Article";
// コマンドを作成する
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
// コマンドを実行
SqlDataReader reader = cmd.ExecuteReader();
// DataTable を作成する
DataTable dt = new DataTable();
// SqlDataReader からデータを DataTable に読み込む
dt.Load(reader);
//while (reader.Read()) // 1 行ずつ読み込む場合
//{
// Debug.WriteLine("Id: {0} - Content: {1}",
// reader["Id"], reader["Content"]);
//}
// リーダーを閉じる
reader.Close();
// 接続を閉じる
conn.Close();
参考情報:
10 行でズバリ !! 接続型のデータ アクセス (ADO.NET) (C#)
https://code.msdn.microsoft.com/windowsdesktop/10-ADONET-C-4d84bfef