C#

(C#) dataGridView에 테이블 출력하기:DataSet DataAdapter

코딩ABC 2023. 6. 25. 07:39
반응형

SQL Server로 부터 데이터를 가져와서 dataGridView 컨트롤에 출력하는 예제입니다.

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace DataSet_1
{
    public partial class Form1 : Form
    {
         public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string connectionString = "server=___;uid=___;pwd=___;database=haksa";
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();

            string sql = "select hakbun,name,tel from student";
            SqlCommand cmd = new SqlCommand(sql, conn);

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;

            DataSet ds = new DataSet();

            DataTable dt = ds.Tables["student"];
            da.Fill(ds, "t1");
            dataGridView1.DataSource = ds.Tables["t1"];
            conn.Close();
        }
    }
}

(Output)

 

반응형