public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //把cities表中的数据加载到窗体的datagridview string connString = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; using(SqlConnection sqlconn=new SqlConnection(connString)) { string selectstring = @"select id, cityid, city, provinceid from cities;select * from provinces"; #region 单张表 //创建一个适配器类 //using(SqlDataAdapter sqladapter=new SqlDataAdapter(selectstring,sqlconn)) //{ // //此时adapter已经连接到了一个表 // DataTable dataTable = new DataTable(); // //将关联表的数据填充到dataTable // //sqladapter会自动打开数据库连接,并执行sql脚本 // sqladapter.Fill(dataTable); // //this.dataGridView1.DataSource = dataTable; // List<cities> mycitylist = new List<cities>(); // //类定义时字段{get;set;}不写显示不出来 // foreach(DataRow datarow in dataTable.Rows) // { // Console.WriteLine(datarow["id"]+" "+datarow[1]); // //把每一行数据封装成city类 // mycitylist.Add(new cities(){ // id=int.Parse(datarow["id"].ToString()), // cityid=int.Parse(datarow["cityid"].ToString()), // city=datarow["city"].ToString(), // provinceid = int.Parse(datarow["provinceid"].ToString()) // }); // } // //把datatable的数据转储成List<city>类型 // this.dataGridView1.DataSource = mycitylist; #endregion #region 多张表 using(SqlDataAdapter sqlDataAdapter =new SqlDataAdapter(selectstring,sqlconn)) { DataSet dataset=new DataSet(); sqlDataAdapter.Fill(dataset); this.dataGridView1.DataSource = dataset.Tables[0]; } #endregion } } }