C#--数据库初体验

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        SqlConnection cn;
        public Form1()
        {
            InitializeComponent();
        }

        public SqlConnection getCN()
        {
            string strCN = "Data Source=.\\SQLEXPRESS;Initial Catalog=model;Integrated Security=True";
            cn = new SqlConnection(strCN);
            return cn;
        }


        private void Form1_Load(object sender, EventArgs e)
        {
        cn = getCN();
            try
            {
               cn.Open();
                string strSQL = "select * from Table1 ";
                SqlDataAdapter da = new SqlDataAdapter(strSQL, cn);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];

                SqlCommand cmd = new SqlCommand(strSQL, cn);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                   if (!listBox1.Items.Contains (dr[1]))
                    {
                        listBox1.Items.Add(dr[1]);
                    }                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cn.Dispose();
            }      

        }
    }
}

C#--数据库初体验_第1张图片

你可能感兴趣的:(C#--数据库初体验)