C#的winform连接SQLserver数据库实例代码


创建一个winform窗口,添加两个按钮,一个datagridview控件和一个listview控件

连接和绑定datagridview控件的代码

            SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=ch19930310;database=student;");
            SqlDataAdapter dtp = new SqlDataAdapter("SELECT * FROM student", con);
            DataSet ds = new DataSet();
            dtp.Fill(ds);//填充数据集

            dataGridView1.DataSource = ds.Tables[0].DefaultView;   //连接数据表格,显示数据
            con.Close();    //关闭OleDbConnection对象实例

 

连接和绑定listview控件的代码

          SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=ch19930310;database=student;");
            SqlDataAdapter dtp = new SqlDataAdapter("SELECT * FROM student", con);
            try
            {
                con.Open();
                SqlDataAdapter sda = new SqlDataAdapter("select st_id,st_name,st_birth,st_gender,st_address,st_tel,st_clid from student", con);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                this.listView1.Columns.Add("学号", 80, HorizontalAlignment.Center);//增加列标题
                this.listView1.Columns.Add("姓名", 60, HorizontalAlignment.Center);//增加列标题
                this.listView1.Columns.Add("生日", 120, HorizontalAlignment.Center);//增加列标题
                this.listView1.Columns.Add("性别", 40, HorizontalAlignment.Center);//增加列标题
                this.listView1.Columns.Add("地址", 90, HorizontalAlignment.Center);//增加列标题
                this.listView1.Columns.Add("电话", 90, HorizontalAlignment.Center);//增加列标题
                this.listView1.Columns.Add("班级", 60, HorizontalAlignment.Center);//增加列标题
                listView1.View = View.Details;
                listView1.GridLines = true;//显示网格线。
                string[] str = new string[7];
                foreach (DataRow row in ds.Tables[0].Rows)
                {

                    str[0] = row["st_id"].ToString();
                    str[1] = row["st_name"].ToString();
                    str[2] = row["st_birth"].ToString();
                    str[3] = row["st_gender"].ToString();
                    str[4] = row["st_address"].ToString();
                    str[5] = row["st_tel"].ToString();
                    str[6] = row["st_clid"].ToString();
                    ListViewItem item = new ListViewItem(str, 0);
                    listView1.Items.Add(item);

                }
            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString());
                con.Close();
            }

 

 

代码很简单,多看就理解了


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM