C#でSQLServerに接続してGridViewにデータのセットまで

スポンサーリンク

はじめに

ASP.NETでウェブアプリを作っていて、SQLServerからテーブルのデータを取得してWebで表示するために色々調べたのでまとめます。

Web.configへの記述

SQLServerのデータベースへの接続は下のように「Web.config」に接続情報を追加することから始めます。

<?xml version="1.0" encoding="utf-8"?>
<!--
  ASP.NET アプリケーションの構成方法の詳細については、
  https://go.microsoft.com/fwlink/?LinkId=169433 を参照してください
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
	<!--接続情報-->
	<connectionStrings>
		<add name="sqlserver"
			 connectionString="Data Source=(SQLServer名);Initial Catalog=(データベース名);Integrated Secutiry=False;UserID=(ユーザー名);Password=(パスワード)"
			 providerName="System.Data.SqlClient"/>
	</connectionStrings>
</configuration>

WebForm.aspx.csへの記述

データベースに接続して、ストアドなどの処理を流すための記述は下のようになります。

WebForm.aspxではデフォルトの状態にGridViewを1つ追加しただけです。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//接続情報取得用
using System.Configuration;
//SqlConnection用
using System.Data.SqlClient;
//ストアド利用でCommandType用
using System.Data;

namespace Test
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var db = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;
            using (var connection = new SqlConnection(db))
            using (var cm = new SqlCommand())
            {
                connection.Open();
                cm.Connection = connection;
                cm.CommandType = CommandType.StoredProcedure;
                cm.CommandText = "(ストアド名)";

                //結果セットを取得せず実行するだけの場合
                cm.ExecuteNonQuery();

                //結果セットを取得する場合
                var result = cm.ExecuteReader();
                var list = new List<int>();
                while (result.Read())
                {
                    //リストに結果を格納するなど1行ごとの処理を書く
                    list.Add(0);
                }
                //GridViewのデータソースを指定
                GridView1.DataSource = list;
                //データのセット
                GridView1.DataBind();

            }
        }
    }
}

まとめ

無事にSQLServerに接続し、データの取得と表示まで出来ました。

コメント

タイトルとURLをコピーしました