Chả là em có bài tập tạo winform có kết nối với Cơ sở dữ liệu sql server,
nhưng không hiểu sao nó không hiển thị dữ liệu ở sql server
Đoạn code như sau:
Summary
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace BTTH_ADO
{
public partial class FormEmployee : Form
{
public FormEmployee()
{
InitializeComponent();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void FormEmployee_Load(object sender, EventArgs e)
{
LayDLDataGridview();
LayDLTenPB();
}
private void LayDLDataGridview()
{
string connetionString = null;
SqlConnection conn;
connetionString = @"Data Source = ADMIN - PC\MAITHIVAN;Initial Catalog = QLNS; Integrated Security = True;Password=12345678";
conn = new SqlConnection(connetionString);
try {
conn.Open();
string sql = "select * from Employees";
SqlCommand com = new SqlCommand(sql, conn);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
this.dataGridView1.DataSource = dt;
}
catch(Exception)
{
MessageBox.Show("Không lấy đc nội dung bang data. Lỗi rồi");
}
conn.Close();
}
private void LayDLTenPB()
{
SqlConnection conn;
string connstring = @"Data Source = ADMIN - PC\MAITHIVAN;Initial Catalog = QLNS; Integrated Security = True;Password=12345678";
conn = new SqlConnection(connstring);
try {
conn.Open();
string sql = "select DepartmentID,DepartmentName from Departments";
SqlCommand com = new SqlCommand(sql, conn);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
this.comboBoxTenPB.DataSource = dt;
this.comboBoxTenPB.DisplayMember = "DepartmentName";
this.comboBoxTenPB.ValueMember = "DepartmentID";
}
catch(SqlException)
{
MessageBox.Show("Không lấy đc nội dung Tên PB. Lỗi rồi");
}
conn.Close();
DialogResult tl;
tl = MessageBox.Show("Chắc không?", "Trả lời", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (tl == DialogResult.OK) Application.Exit();
}
}
}
Code không có error nào và vẫn chạy nhưng không hiển thị:
Dữ liệu trong SQL server đã tạo: