在线答题系统

辅助类:

DBHelper类:包括数据库连接字符串、数据库连接对象两个静态公有字段。

View Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace MySchool
{
    // 存放数据库连接字符串和数据库连接对象
    class DBHelper
    {
        // 数据库连接字符串        
        public static string connectionString = "Data Source=.;Initial Catalog=MySchool;uid=sa;pwd=sa";
        // 数据库连接对象
        public static SqlConnection connection = new SqlConnection(connectionString);
    }
}

UserHelper类:包括当前登录用户名、登录类型两个静态公有字段。

View Code
using System;
using System.Collections.Generic;
using System.Text;

namespace MySchool
{
    // 用来记录登录的用户名、登录类型
    class UserHelper
    {
        public static string loginId;    // 登录用户名
        public static string loginType;  // 登录类型
    }
}

QuizHelper类:题目的一些信息。

View Code
using System;
using System.Collections.Generic;
using System.Text;

namespace MySchool
{
    class QuizHelper
    {
        public static int totalSeconds = 1200; // 答题总时间20分钟
        public static int remainSeconds;       // 剩余的时间

        public static int[] allQuestionIds;    // 所有问题的Id数组
        public static bool[] selectedStates;   // 记录对应索引的问题是否已经被随机抽中

        public static int questionNum = 20;                        // 题目数量
        public static int[] selectedQuestionIds = new int[20];     // 选出的问题Id数组        
        public static string[] correctAnswers = new string[20];    // 标准答案数组
        public static string[] studentAnswers = new string[20];    // 学员的答案   
        
    }
}

登录窗口:

View Code
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;

namespace MySchool
{
    /// <summary>
    /// 登录窗体
    /// </summary>
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        // “登录”按钮的单击事件
        private void btnLogin_Click(object sender, EventArgs e)
        {
            bool isValidUser = false;   // 标识是否为合法用户            
            string message = "";

            if (ValidateInput())  // 验证输入成功,显示窗体
            {
                // 验证用户是否为合法用户
                isValidUser = ValidateUser(
                    txtLoginId.Text,
                    txtLoginPwd.Text,
                    cboLoginType.Text,
                    ref message
                    );

                // 如果是合法用户,就转到相应的窗体
                if (isValidUser)
                {
                    // 记录登录用户名和登录类型
                    UserHelper.loginId = txtLoginId.Text;
                    UserHelper.loginType = cboLoginType.Text;

                    switch (cboLoginType.Text)
                    { 
                        case "学员":
                            // 试题选择窗体对象
                            StudentForm studentForm = new StudentForm();
                            // 显示窗体
                            studentForm.Show();
                            break;
                        default:
                            MessageBox.Show("抱歉,功能尚未开通!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                            break;
                    }

                    // 登录窗体隐藏
                    this.Visible = false;                    
                }
                else  // 验证合法用户失败,给出提示
                {
                    MessageBox.Show(message,"登录提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
            } 
        }

        // 验证用户的输入
        // 成功返回 True,失败返回 False
        private bool ValidateInput()
        {
            if (txtLoginId.Text.Trim() == "")
            {
                MessageBox.Show("请输入用户名", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtLoginId.Focus();
                return false;
            }
            else if (txtLoginPwd.Text.Trim() == "")
            {
                MessageBox.Show("请输入密码", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtLoginPwd.Focus();
                return false;
            }
            else if (cboLoginType.Text.Trim() == "")
            {
                MessageBox.Show("请选择登录类型", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cboLoginType.Focus();
                return false;
            }
            else
            {
                return true;
            }
        }

        // 验证用户是否合法
        // 传入用户名、密码、登录类型
        // 合法返回 True,不合法返回 False
        // message 参数用来记录验证失败的原因
        private bool ValidateUser(string loginId, string loginPwd, string loginType, ref string message)
        {
            string tableName = "";  // 要查询的数据表的名称
            bool result = true;     // 返回值

            // 根据登录类型,确定数据表名称
            switch (loginType)
            { 
                case "教员":
                    tableName = "Teacher";
                    break;
                case "学员":
                    tableName = "Student";
                    break;
                case "管理员":
                    tableName = "Admin";
                    break;
                default:
                    message = "登录类型错误!";
                    result = false;
                    break;                  
            }            

            // 查询字符串
            string sql = string.Format(
                "SELECT COUNT(*) FROM {0} WHERE LoginId='{1}' AND LoginPwd='{2}'",
                tableName,loginId, loginPwd);

            try
            {
                // 创建 Command 对象
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);

                // 打开数据库连接
                DBHelper.connection.Open();

                // 验证是否为合法用户
                int count = (int)command.ExecuteScalar();
                if (count < 1)
                {
                    message = "用户名或密码不存在!";
                    result = false;
                }
                else
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                message = "操作数据库出错!";
                Console.WriteLine(ex.Message);
                result = false;
            }
            finally
            {
                // 关闭数据库连接
                DBHelper.connection.Close();
            }            

            return result;
        }

        // 退出登录
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

学生答题主窗口:
学生答题主窗口是MDI父窗口

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

namespace MySchool
{
    /// <summary>
    /// 学员登录后的主窗体
    /// </summary> 
    public partial class StudentForm : Form
    {
        public StudentForm()
        {
            InitializeComponent();
        }

        // 单击“退出”菜单项时,退出应用程序
        private void tsmiExit_Click(object sender, EventArgs e)
        {
            // 弹出消息框向用户确认
            DialogResult result = MessageBox.Show("确定要退出吗?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
           
            // 如果选择了“是”,退出应用程序
            if (result == DialogResult.Yes)
            {
                Application.Exit();
            }            
        }        

        // 点击菜单中的“帮助”->”关于”,以模式窗口显示 About 窗体
        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            AboutForm aboutForm = new AboutForm();
            aboutForm.ShowDialog();  // 以模式窗口显示
        }

        // 窗体加载事件处理
        private void StudentForm_Load(object sender, EventArgs e)
        {
            // 设置状态栏标签显示的文字
            lblTeacher.Text = string.Format("学员{0}登录了!",UserHelper.loginId);
        }

        // 进入在线答题模块,显示选题窗体
        private void tsmiQuiz_Click(object sender, EventArgs e)
        {
            SelectQuestionsForm selectQuestionsForm = new SelectQuestionsForm();
            selectQuestionsForm.MdiParent = this;
            selectQuestionsForm.Show();
        }

        // 窗体关闭事件
        private void StudentForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }        
    }
}

选择科目题目的窗口:

View Code
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;

namespace MySchool
{
    /// <summary>
    /// 试题选择窗体
    /// </summary>
    public partial class SelectQuestionsForm : Form
    {
        public SelectQuestionsForm()
        {
            InitializeComponent();
        }

        // 窗体加载时,将科目从数据库中读取出来显示在组合框中
        private void SelectQuestionsForm_Load(object sender, EventArgs e)
        {
            bool error = false;  // 表示操作数据库是否出错

            string sql = "SELECT SubjectName FROM Subject";  // 查询用sql语句

            try
            {
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);
                DBHelper.connection.Open();
                // 执行查询
                SqlDataReader dataReader = command.ExecuteReader();

                // 循环添加到组合框中
                while (dataReader.Read())
                {
                    cboSubjects.Items.Add(dataReader["SubjectName"].ToString());
                }
                dataReader.Close();
            }
            catch (Exception ex)
            {                
                error = true;
                Console.WriteLine(ex.Message);
            }
            finally
            {
                DBHelper.connection.Close();
            }

            if (error)  // 出错了
            {
                MessageBox.Show("数据库操作出错,请稍候再试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 放弃答题,退出应用程序
        private void btnGiveUp_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("还没有开始做题,真的要放弃吗?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                this.Close();
            }
        }

        // 单击“开始答题”按钮
        private void btnBegin_Click(object sender, EventArgs e)
        {
            if (cboSubjects.SelectedIndex == -1)
            {
                MessageBox.Show("请选择科目!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cboSubjects.Focus();                
            }
            else
            {
                // 获得选中科目的Id
                int subjectId = GetSubjectId(cboSubjects.Text);

                // 该科目问题总数
                int allQuestionCount = GetQuestionCount(subjectId);

                // 指定所有问题数组的长度                
                QuizHelper.allQuestionIds = new int[allQuestionCount];

                // 指定记录问题是否选中的数组的长度
                QuizHelper.selectedStates = new bool[allQuestionCount];

                // 为所有问题数组元素赋值
                SetAllQuestionIds(subjectId);

                // 抽题
                SetSelectedQuestionIds();

                // 取出标准答案
                SetRightAnswers();

                // 剩余时间为20分钟
                QuizHelper.remainSeconds = 1200;

                // 将学生答案数组初始化
                for (int i = 0; i < QuizHelper.studentAnswers.Length; i++)
                {
                    QuizHelper.studentAnswers[i] = "未回答";
                }

                // 打开答题窗体
                AnswerQuestionForm answerQuestion = new AnswerQuestionForm();
                answerQuestion.MdiParent = this.MdiParent;
                answerQuestion.Show();
                this.Close();
            }
        }

        // 获得对应科目的题目的总数
        private static int GetQuestionCount(int subjectId)
        {

            int questionCount = 0; // 该科目的题目总数
            string sql = "SELECT COUNT(*) FROM Question WHERE SubjectId=" + subjectId;
            try
            {
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);
                DBHelper.connection.Open();
                questionCount = Convert.ToInt32(command.ExecuteScalar());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                DBHelper.connection.Close();
            }
            return questionCount;
        }

        // 获得科目的Id
        private int GetSubjectId(string subjectName)
        {
            int subjectId = -1;  // 科目的Id
            // 查询语句
            string sql = string.Format(
                "SELECT SubjectId FROM Subject WHERE SubjectName='{0}'",
                subjectName);
            try
            {
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);
                DBHelper.connection.Open();
                subjectId = Convert.ToInt32(command.ExecuteScalar());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                DBHelper.connection.Close();
            }
            return subjectId;
        }

        // 获得某科目所有问题的Id
        private void SetAllQuestionIds(int subjectId)
        {
            string sql = "SELECT QuestionId FROM Question WHERE SubjectId="+subjectId;
            try
            {
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);
                DBHelper.connection.Open();
                SqlDataReader dataReader = command.ExecuteReader(); // 执行查询
                
                // 为数组元素赋值
                for (int i = 0; i < QuizHelper.allQuestionIds.Length; i++)
                {
                    if (dataReader.Read())
                    {
                        // 为所有问题Id数组元素赋值
                        QuizHelper.allQuestionIds[i] = Convert.ToInt32(dataReader["QuestionId"]);                        
                        // 所有问题都是被选问题
                        QuizHelper.selectedStates[i] = false;
                    }
                }
                dataReader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                DBHelper.connection.Close();
            }
        }

        // 抽取试题
        private void SetSelectedQuestionIds()
        {
            Random random = new Random();
            int questionIndex = 0;  // 随机产生的问题的索引值

            // 抽取每一道题并保存抽出的题目的Id
            int i = 0;  // 记录抽取了几道题
            while (i < QuizHelper.questionNum)
            {
                // 在所有题目的数量范围内抽题产生随机数
                questionIndex = random.Next(QuizHelper.allQuestionIds.Length); 
 
                if (QuizHelper.selectedStates[questionIndex] == false)  // 如果没有被选中过,可以选择
                {
                    QuizHelper.selectedQuestionIds[i] = QuizHelper.allQuestionIds[questionIndex];
                    QuizHelper.selectedStates[questionIndex] = true;
                    i++;
                } 
            }            
        }

        // 取出试题的标准答案
        private void SetRightAnswers()
        {
            try
            {
                string sql = "";  // 查询用sql语句
                SqlCommand command = new SqlCommand();
                command.Connection = DBHelper.connection;
                DBHelper.connection.Open();

                for (int i = 0; i < QuizHelper.selectedQuestionIds.Length; i++)
                {
                    sql = string.Format("SELECT Answer FROM Question WHERE QuestionId={0}",
                        QuizHelper.selectedQuestionIds[i]);
                    command.CommandText = sql;

                    // 为标准答案数组赋值
                    QuizHelper.correctAnswers[i] = command.ExecuteScalar().ToString();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                DBHelper.connection.Close();
            }            
        }
    }
}

答题窗体:

View Code
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;

namespace MySchool
{
    /// <summary>
    /// 答题窗体
    /// </summary>
    public partial class AnswerQuestionForm : Form
    {
        public int questionIndex = 0;  // 当前的问题对应的数组索引

        public AnswerQuestionForm()
        {
            InitializeComponent();
        }        

        // 窗体加载时,显示相应题目的信息
        private void AnswerQuestionForm_Load(object sender, EventArgs e)
        {
            tmrCostTime.Start();   // 启动计时器
            
            GetQuestionDetails();  // 显示题目信息
            CheckOption();      // 如果题目已经答过,让相应的选项选中 
            CheckBtnNext();       // 确定是否到了最后一题
        }

        // 确定“下一题”按钮应该显示的文字
        private void CheckBtnNext()
        {
            // 如果达到20题,就让“下一题”按钮的文字显示为“检查答案”
            if (questionIndex >= QuizHelper.selectedQuestionIds.Length - 1)
            {                
                btnNext.Text = "检查答案";
            }
        }
        
        // 单击“下一题”按钮时,为答案数组赋值,并显示下一题的信息
        private void btnNext_Click(object sender, EventArgs e)
        {
            // 如果没有到最后一题,就继续显示新题目信息
            if (questionIndex < QuizHelper.selectedQuestionIds.Length - 1)
            {
                questionIndex++;
                
                GetQuestionDetails();  // 显示试题信息
                CheckOption();         // 如果题目已经答过,让相应的选项选中    
                CheckBtnNext();       // 确定是否到了最后一题
            }
            else  // 否则,打开答题卡窗体
            {
                OpenAnswerCard();
            }
        }       

        // 打开答题卡窗体
        private void OpenAnswerCard()
        {
            AnswerCardForm answerCardForm = new AnswerCardForm();
            answerCardForm.MdiParent = this.MdiParent;
            answerCardForm.Show();
            this.Close();
        }

        // 计时器事件
        private void tmrCostTime_Tick(object sender, EventArgs e)
        {
            int minute;   // 当前的分钟
            int second;   //// 如果还有剩余时间,就显示剩余的分钟和秒数
            if (QuizHelper.remainSeconds > 0)
            {
                QuizHelper.remainSeconds--; 
                minute = QuizHelper.remainSeconds / 60;
                second = QuizHelper.remainSeconds % 60;
                lblTimer.Text = string.Format("{0:00}:{1:00}", minute, second);  // 补充知识点                                
            }
            // 否则,就提示交卷
            else 
            {
                tmrCostTime.Stop();
                MessageBox.Show("时间到了,该交卷了!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                QuizResultForm quizResultForm = new QuizResultForm();
                quizResultForm.MdiParent = this.MdiParent;
                quizResultForm.Show();
                this.Close();
            }
        }
  
        // 选项单选按钮的单击事件处理,选择答案时,记录答案
        private void rdoOption_Click(object sender, EventArgs e)
        {
            QuizHelper.studentAnswers[questionIndex] = Convert.ToString(((RadioButton)sender).Tag);
        }

        // 单击“答题卡”按钮时,打开答题卡窗体
        private void btnAnswerCard_Click(object sender, EventArgs e)
        {
            OpenAnswerCard();
        }

        // 根据问题的Id,显示题目的详细信息
        public void GetQuestionDetails()
        {
            // 显示当前的题目信息
            lblQuestion.Text = string.Format("问题{0}:", questionIndex + 1);
            
            // 查询题目信息的sql语句
            string sql = "SELECT Question, OptionA, OptionB,OptionC,OptionD FROM Question WHERE QuestionId=" + QuizHelper.selectedQuestionIds[questionIndex];
            try
            {
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);
                DBHelper.connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.Read())
                {
                    lblQuestionDetails.Text = reader["Question"].ToString();  // 题目
                    rdoOptionA.Text = string.Format("A.{0}", reader["OptionA"].ToString());
                    rdoOptionB.Text = string.Format("B.{0}", reader["OptionB"].ToString());
                    rdoOptionC.Text = string.Format("C.{0}", reader["OptionC"].ToString());
                    rdoOptionD.Text = string.Format("D.{0}", reader["OptionD"].ToString());
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                DBHelper.connection.Close();
            }
        }

        // 如果已经答了题目,选中相应的选项
        private void CheckOption()
        {
            switch (QuizHelper.studentAnswers[questionIndex])
            {
                case "A":
                    rdoOptionA.Checked = true;
                    break;
                case "B":
                    rdoOptionB.Checked = true;
                    break;
                case "C":
                    rdoOptionC.Checked = true;
                    break;
                case "D":
                    rdoOptionD.Checked = true;
                    break;
                default:
                    rdoOptionA.Checked = false;
                    rdoOptionB.Checked = false;
                    rdoOptionC.Checked = false;
                    rdoOptionD.Checked = false;
                    break;
            }
        }        
    }
}

答题卡窗口:

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

namespace MySchool
{
    public partial class AnswerCardForm : Form
    {
        public AnswerCardForm()
        {
            InitializeComponent();
        }

        // 计时器的 Tick 事件 
        private void tmrCostTime_Tick(object sender, EventArgs e)
        {
            int minute;   // 当前的分钟
            int second;   //// 如果还剩有答题时间,就显示剩余的时间
            if (QuizHelper.remainSeconds > 0)
            {
                minute = QuizHelper.remainSeconds / 60;
                second = QuizHelper.remainSeconds % 60;
                lblTimer.Text = string.Format("{0:00}:{1:00}", minute, second);  // 补充知识点
                QuizHelper.remainSeconds--;
            }
            // 否则,停止计时,提示交卷
            else 
            {
                tmrCostTime.Stop();
                MessageBox.Show("时间到了,该交卷了!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                QuizResultForm quizResultForm = new QuizResultForm();
                quizResultForm.Show();
                this.Close();
            }
        }

        // 窗体加载时,显示答案
        private void AnswerCardForm_Load(object sender, EventArgs e)
        {
            int index = 0;
            // 遍历窗体上的所有控件
            foreach (Control item in this.Controls)
            {
                // 如果是标签,就获取它的Tag属性的值
                if (item is Label)  
                {
                    index = Convert.ToInt32(item.Tag);

                    // index为-1的那个标签是显示时间的,要排除在外
                    if (index != -1)
                    {
                        item.Text = QuizHelper.studentAnswers[index]; 
                    }                    
                }
            }
            tmrCostTime.Start();  // 启动计时器
        }

        // 交卷
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            // 创建答题结果窗体并显示,关闭当前窗体
            QuizResultForm quizResultForm = new QuizResultForm();
            quizResultForm.MdiParent = this.MdiParent;
            quizResultForm.Show();
            this.Close();
        }        

        // 转到相应的题目
        private void btnQuestion_Click(object sender, EventArgs e)
        {
            // 获得点击的按钮代表的题号
            int questionIndex = Convert.ToInt32(((Button)sender).Tag);

            // 创建回答问题窗体对象
            AnswerQuestionForm answerQuestionForm = new AnswerQuestionForm();

            // 将题目的索引传递到回答问题窗体
            answerQuestionForm.questionIndex = questionIndex;

            // 显示回答问题窗体,关闭当前窗体
            answerQuestionForm.MdiParent = this.MdiParent;
            answerQuestionForm.Show();
            this.Close();
        }        
    }
}

答题结果窗口:

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

namespace MySchool
{
    public partial class QuizResultForm : Form
    {
        public QuizResultForm()
        {
            InitializeComponent();
        }

        // 退出应用程序
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // 显示分数
        private void QuizResultForm_Load(object sender, EventArgs e)
        {
            // 计算答对的题目数量
            int correctNum = 0;  
            for (int i = 0; i < QuizHelper.questionNum; i++)
            {
                if (QuizHelper.studentAnswers[i] == QuizHelper.correctAnswers[i])
                {
                    correctNum++;
                }
            }

            // 计算得分
            int score = correctNum * 100 / QuizHelper.questionNum;
            lblMark.Text = score.ToString()+"";

            // 确定显示分数的label的宽度
            lblStudentScoreStrip.Width = lblFullMarkStrip.Width * score / 100;
            
            // 根据不同的得分,显示不同的颜色
            if (score < 60)
            {
                lblStudentScoreStrip.BackColor = Color.Red;
                lblComment.Text = "该好好复习啦!";
                picFace.Image = ilFaces.Images[0];
            }
            else if (score >= 60 && score < 85)
            {
                lblStudentScoreStrip.BackColor = Color.Blue;
                lblComment.Text = "还不错,继续努力哦!";
                picFace.Image = ilFaces.Images[1];
            }
            else if (score >= 85 && score < 100)
            {
                lblStudentScoreStrip.BackColor = Color.CornflowerBlue;
                lblComment.Text = "真厉害,得了优秀呢!";
                picFace.Image = ilFaces.Images[2];
            }
            else if (score == 100)
            {
                lblStudentScoreStrip.BackColor = Color.Green;
                lblComment.Text = "你真棒,全都答对了!";
                picFace.Image = ilFaces.Images[3];
            }
        }
    }
}
原文地址:https://www.cnblogs.com/tangzhengyue/p/2693486.html