前期准备

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;






public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        void initLV(ListView l)
        {
            l.MultiSelect = false;
            l.GridLines = true;
            l.FullRowSelect = true;
            l.View = View.Details;
        }

        void loadLV(ListView l, string sql)
        {
            try
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(sql, con);
                DataTable dt = new DataTable();
                da.Fill(dt);
                l.Items.Clear();
                l.Columns.Clear();
                int i, j;
                for (i = 0; i < dt.Columns.Count; i++)
                    l.Columns.Add(dt.Columns[i].Caption, (l.Width - 4) / dt.Columns.Count);
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    ListViewItem li = new ListViewItem();
                    li.SubItems[0].Text = dt.Rows[i][0].ToString().Trim();
                    for (j = 1; j < dt.Columns.Count; j++)
                    {
                        string s = dt.Rows[i][j].ToString().Trim();
                        try
                        {
                            DateTime dtime = DateTime.Parse(s);
                            li.SubItems.Add(dtime.Date.ToShortDateString());
                        }
                        catch
                        {
                            li.SubItems.Add(s);
                        }
                    }
                    l.Items.Add(li);
                }
            }
            catch { }
            finally { con.Close(); }
        }

        SqlConnection con = new SqlConnection();





        void loadCB(ComboBox c, string sql)
        {
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = sql;
                SqlDataReader rd = cmd.ExecuteReader();
                c.Items.Clear();
                while (rd.Read()) c.Items.Add(rd.GetValue(0).ToString().Trim());
            }
            catch { }
            finally { con.Close(); }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            con.ConnectionString = @"server=.\chen;database=b2014;integrated security=true";
            initLV(listView1);

            loadCB(comboBox1, "select tname from teachers");
            loadCB(comboBox2, "select tno from teachers");


        }

你可能感兴趣的:(前期准备)