码迷,mamicode.com
首页 > Windows程序 > 详细

使用winform开发的背单词小程序

时间:2015-06-25 06:44:08      阅读:838      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;

namespace yasi
{
    public partial class Form1 : Form
    {
        public int len = -1;
        DataTable table = new DataTable();//datagridview1全局的table
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DataGridViewButtonColumn button = new DataGridViewButtonColumn();
            button.HeaderText = " 删除按钮";
            button.Text = "删除";
            button.UseColumnTextForButtonValue = true;
            this.dataGridView1.Columns.AddRange(button);
            chaxun();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            chaxun();
            //选择开头字母
            #region
            switch (comboBox1.Text.Trim())
            {
                case "显示全部":
                    chaxun();
                    break;
                case "A":
                    chaxun("‘a‘");
                    break;
                case "B":
                    chaxun("‘b‘");
                    break;
                case "C":
                    chaxun("‘c‘");
                    break;
                case "D":
                    chaxun("‘d‘");
                    break;
                case "E":
                    chaxun("‘e‘");
                    break;
                case "F":
                    chaxun("‘f‘");
                    break;
                case "G":
                    chaxun("‘g‘");
                    break;
                case "H":
                    chaxun("‘h‘");
                    break;
                case "I":
                    chaxun("‘i‘");
                    break;
                case "J":
                    chaxun("‘j‘");
                    break;
                case "K":
                    chaxun("‘k‘");
                    break;
                case "L":
                    chaxun("‘l‘");
                    break;
                case "M":
                    chaxun("‘m‘");
                    break;
                case "N":
                    chaxun("‘n‘");
                    break;
                case "O":
                    chaxun("‘o‘");
                    break;
                case "P":
                    chaxun("‘p‘");
                    break;
                case "Q":
                    chaxun("‘q‘");
                    break;
                case "R":
                    chaxun("‘r‘");
                    break;
                case "S":
                    chaxun("‘s‘");
                    break;
                case "T":
                    chaxun("‘t‘");
                    break;
                case "U":
                    chaxun("‘u‘");
                    break;
                case "V":
                    chaxun("‘v‘");
                    break;
                case "W":
                    chaxun("‘w‘");
                    break;
                case "Y":
                    chaxun("‘y‘");
                    break;
                case "Z":
                    chaxun("‘z‘");
                    break;
                default:
                    MessageBox.Show("妹子你姿势不对啊!");
                    break;
            }
            #endregion
        }
        public void chaxun()
        {
            table.Clear();
            SQL sqlString = new SQL();
            SqlCommand cmd = sqlString.GetSqlStringCommand("select 单词,词义 from xz");
            table = sqlString.ExecuteDataTable(cmd);
            dataGridView1.DataSource = table;
            len = table.Rows.Count;
        }
        public void chaxun(string hdm)
        {
            table.Clear();
            SQL sqlString = new SQL();
            SqlCommand cmd = sqlString.GetSqlStringCommand("select 单词,词义 from xz where 标志= " + hdm);
            table = sqlString.ExecuteDataTable(cmd);
            dataGridView1.DataSource = table;
            len = table.Rows.Count;
        }
        public int Chaos_GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }
        public int[] hash(int i,int max)//生成随机函数,i数组的长度,max表示table长度,返回一个随机数组
        {
            int[] a = new int[i];
            for (int j = 0; j < i; j++)
            {
                bool flag = false;
                Random ran = new Random(Chaos_GetRandomSeed());
                int k = ran.Next(0, max);
                foreach (int t in a)//判断是否已经存在相等的数字,若存在flag置为true
                {
                    if (t == k)
                    {
                        flag = true;
                    }
                }
                if (flag)
                {
                    j--;
                }
                else
                {
                    a[j] = k;
                }
            }
            return a;
        }
        public int[] Bubble_Sort(int[] a)//从小到大
        {
            for (int i = 0; i < a.Length - 1;i++ )
            {
                for (int j = 0; j < a.Length - 1;j++ )
                {
                    if(a[j]>a[j+1])
                    {
                        int temp = a[j];
                        a[j] = a[j + 1];
                        a[j + 1] = temp;
                    }
                }
            }
            return a;
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //此处加一个之前选择的标志符,以符号名称来判断是选择使用哪一个表格
            if (e.ColumnIndex == 0)
            {
                string word = "";
                word = Convert.ToString(dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value).Trim();
                SQL sqlString = new SQL();
                SqlCommand cmd = sqlString.GetSqlStringCommand("delete from xz where 单词 =" + string.Format("‘{0}‘", word)); 
                sqlString.ExecuteNonQuery(cmd);
                chaxun();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataTable tableOne = table;
            int num=0;
            switch (comboBox2.Text.Trim().ToString())
            {
                case "10":
                    num = 10;
                    break;
                case "30":
                    num = 30;
                    break;
                case "50":
                    num = 50;
                    break;
                case "100":
                    num = 100;
                    break;
                default:
                    MessageBox.Show("妹子不要抽象啊!");
                    break;
            }
            int[] a = new int[num];
            if(num>len)
            {
                num = len;
            }
            a = hash(num, len);
            int[] b = new int[num];
            string str = "";
            b = Bubble_Sort(a);

            //测试用
            #region
            foreach (int t in b)
            {
                str += t.ToString() + " ";
            }
            MessageBox.Show(str);
            #endregion

            #region
            table = tableOne.Clone();
            table.Clear();
            foreach(int i in b)
            {
                table.ImportRow(tableOne.Rows[i-1]);
            }
            #endregion
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = table;
        }

        //保存当前页面的单词到word
        private void button3_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            ExportDataGridViewToWord(table,sfd);
        }
        //理解再加以修改
        public void ExportDataGridViewToWord(DataTable srcDgv, SaveFileDialog sfile)
        {
            if (srcDgv.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                sfile.AddExtension = true;
                sfile.DefaultExt = ".doc";
                sfile.Filter = "(*.doc)|*.doc";
                if (sfile.ShowDialog() == DialogResult.OK)
                {

                    object path = sfile.FileName;
                    Object none = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    Microsoft.Office.Interop.Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                    //建立表格
                    Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count, srcDgv.Columns.Count, ref none, ref none);
                    try
                    {
                        table.Columns[1].Width = 130f;
                        for (int i = 0; i < srcDgv.Columns.Count; i++)//输出标题
                        {

                            table.Cell(1, i + 1).Range.InsertAfter(srcDgv.Columns[i].ColumnName);

                        }

                        //输出控件中的记录

                        for (int i = 0; i < srcDgv.Rows.Count;++i)
                        {
                            for (int j = 0; j < srcDgv.Columns.Count; j++)
                            {
                                table.Cell(i + 2, j + 1).Range.InsertAfter(srcDgv.Rows[i][j].ToString());
                            }

                        }
                        //去掉了格子,加上会增加格子
                        //table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        //table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);


                        MessageBox.Show("数据已经成功导出到:" + sfile.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "提示", MessageBoxButtons.OK);
                    }
                }
            }

        }
    }
}

效果截图
技术分享

配置的SQL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace yasi
{
    class SQL
    {
        /// <summary>
        /// 获取数据库连接字符串
        /// </summary>
        private static string ConnectionString
        {
            get
            {
                return Properties.Settings.Default.yasiConnectionString;
            }
        }
        private SqlConnection conn;
        /// <summary>
        /// 构造函数,初始化连接对象
        /// </summary>
        public SQL()
        {
            this.conn = new SqlConnection(ConnectionString);
        }
        /// <summary>
        /// 创建存储过程命令
        /// </summary>
        /// <param name="storedProcdure">存储过程名称</param>
        /// <returns>创建的命令</returns>
        public SqlCommand GetStoredProcCommand(string storedProcdure ,SqlParameter[] parameters=null)
        {
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = storedProcdure;
            cmd.CommandType = CommandType.StoredProcedure;
            if(parameters!=null)
            {
                cmd.Parameters.AddRange(parameters);
            }
            return cmd;
        }
        /// <summary>
        /// 创建文本命令
        /// </summary>
        /// <param name="sql">命令文本</param>
        /// <returns>创建的命令</returns>
        public SqlCommand GetSqlStringCommand(string sql,SqlParameter[] parameters=null)
        {
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            if (parameters != null)
            {
                cmd.Parameters.AddRange(parameters);
            }
            return cmd;
        }
        //执行没有查询结果的命令,返回受影响的行数
        public int  ExecuteNonQuery(SqlCommand cmd)
        {
            int r = -1;
            try
            {
                cmd.Connection.Open();
                r = cmd.ExecuteNonQuery();
                cmd.Connection.Close();
            }
            catch (Exception e)
            {
                
                throw new Exception(e.Message,e);
            }
            return r;
        }
        //执行查询命令,返回数据表
        public DataTable ExecuteDataTable(SqlCommand cmd)
        {
            DataTable table = new DataTable();
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            adapter.Fill(table);
            return table;
        }
    }
}

数据库配置文件
App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="yasi.Properties.Settings.yasiConnectionString" connectionString="Data Source=.;Initial Catalog=yasi;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

 

使用winform开发的背单词小程序

标签:

原文地址:http://www.cnblogs.com/xz-blogs/p/4599082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!