C#
(C#) dataGridView에 데이터베이스 테이블 출력하기
코딩ABC
2023. 4. 19. 07:03
반응형
데이터그리드뷰(dataGridView) 컨트롤에 "haksa" 데이터베이스의 "student" 테이블을 출력하는 C# 코드입니다.
다음 코드를 실습하기 위해서는 아래와 같은 구성이 필요합니다.
1. LocalDB
2. 학사(haksa) 데이터베이스와 학생(student) 테이블 - 다운로드 및 데이터베이스 연결하기
LocalDB 설치와 "haksa" 데이터베이스가 있어야 실행됩니다.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace dataGridView_1
{
public partial class Form1 : Form
{
string connectionString =
@"Server=(LocalDB)\MSSQLLocalDb;database=haksa;integrated security=true";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connectionString;
conn.Open();
string sql = "select * from student order by hakbun";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sql;
cmd.Connection= conn;
SqlDataAdapter da= new SqlDataAdapter();
da.SelectCommand= cmd;
DataSet ds = new DataSet();
da.Fill(ds, "std");
dataGridView1.DataSource= ds.Tables["std"];
}
}
}
다음과 같은 dataGridView 컨트롤과 관련된 코드를 추가할 수 있습니다.
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows= false;
dataGridView1.AllowUserToDeleteRows= false;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.SelectionMode= DataGridViewSelectionMode.FullRowSelect;
}
반응형