C# winform 读取数据库并显示成datagrid
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
}
private void button1_Click(object sender, EventArgs e) {
//string sql = "select * from persons";
//string connectstr = @"Password=myPassword;Persist Security Info=True;User ID=sa;Initial Catalog=TESTDB;Data Source=IETEST\SQLEXPRESS";
//using (SqlConnection conn = new SqlConnection(connectstr)) {
// conn.Open();
// SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
// DataSet ds = new DataSet();
// ada.Fill(ds);
// dataGridView1.DataSource = ds.Tables[0];
//};
string sql = "select * from persons";
string conectionStr = @"Password=sa123456;Persist Security Info=True;User ID=sa;Initial Catalog=TESTDB;Data Source=IEGUORENJIE\SQLEXPRESS";
using (SqlConnection conn = new SqlConnection(conectionStr)) {
conn.Open();
SqlDataAdapter ada = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
ada.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
private void toolStripMenuItem1_Click(object sender, EventArgs e) {
}
private void 图1ToolStripMenuItem_Click(object sender, EventArgs e) {
}
}
}