using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Configuration;
using System.ComponentModel;
namespace VocabularyBookSystem
{
public partial class MainForm : Form
{
private readonly WordRepository _repository;
private BindingSource _bindingSource = new BindingSource();
// 控件声明
private TextBox txtWord;
private TextBox txtMeaning;
private TextBox txtExample;
private DataGridView dgvWords;
public MainForm()
{
InitializeComponent();
_repository = new WordRepository();
InitializeDataGridView();
LoadAllWords();
}
private void InitializeComponent()
{
// 窗体设置
this.Text = "单词管理系统";
this.Size = new Size(850, 600);
this.StartPosition = FormStartPosition.CenterScreen;
this.BackColor = Color.FromArgb(245, 249, 252);
this.Font = new Font("Segoe UI", 10);
// 主面板
Panel mainPanel = new Panel { Dock = DockStyle.Fill };
this.Controls.Add(mainPanel);
// 输入面板
Panel inputPanel = new Panel
{
Dock = DockStyle.Top,
Height = 180,
BackColor = Color.White,
Padding = new Padding(15)
};
mainPanel.Controls.Add(inputPanel);
// 单词输入
Label lblWord = new Label
{
Text = "单词:",
Location = new Point(15, 20),
AutoSize = true
};
inputPanel.Controls.Add(lblWord);
txtWord = new TextBox
{
Location = new Point(80, 15),
Size = new Size(300, 30)
};
inputPanel.Controls.Add(txtWord);
// 释义输入
Label lblMeaning = new Label
{
Text = "释义:",
Location = new Point(15, 65),
AutoSize = true
};
inputPanel.Controls.Add(lblMeaning);
txtMeaning = new TextBox
{
Location = new Point(80, 60),
Size = new Size(300, 30)
};
inputPanel.Controls.Add(txtMeaning);
// 例句输入
Label lblExample = new Label
{
Text = "例句:",
Location = new Point(15, 110),
AutoSize = true
};
inputPanel.Controls.Add(lblExample);
txtExample = new TextBox
{
Location = new Point(80, 105),
Size = new Size(300, 30),
Multiline = true,
Height = 60
};
inputPanel.Controls.Add(txtExample);
// 按钮面板
FlowLayoutPanel btnPanel = new FlowLayoutPanel
{
Dock = DockStyle.Top,
Height = 50,
BackColor = Color.FromArgb(240, 245, 250),
FlowDirection = FlowDirection.LeftToRight,
Padding = new Padding(10, 10, 0, 0)
};
mainPanel.Controls.Add(btnPanel);
// 创建按钮
var buttons = new[]
{
new Button { Text = "添加", Name = "btnAdd", BackColor = Color.FromArgb(65, 105, 225), ForeColor = Color.White, Size = new Size(80, 35) },
new Button { Text = "删除", Name = "btnDelete", BackColor = Color.FromArgb(220, 80, 60), ForeColor = Color.White, Size = new Size(80, 35) },
new Button { Text = "修改", Name = "btnUpdate", BackColor = Color.FromArgb(65, 105, 225), ForeColor = Color.White, Size = new Size(80, 35) },
new Button { Text = "查询", Name = "btnSearch", BackColor = Color.FromArgb(60, 179, 113), ForeColor = Color.White, Size = new Size(80, 35) },
new Button { Text = "测试", Name = "btnTest", BackColor = Color.FromArgb(184, 134, 11), ForeColor = Color.White, Size = new Size(80, 35) }
};
foreach (var btn in buttons)
{
btn.Click += Button_Click;
btn.FlatStyle = FlatStyle.Flat;
btn.FlatAppearance.BorderSize = 0;
btn.Font = new Font("Segoe UI", 9, FontStyle.Bold);
btnPanel.Controls.Add(btn);
}
// 数据表格
dgvWords = new DataGridView
{
Dock = DockStyle.Fill,
AutoGenerateColumns = false,
AllowUserToAddRows = false,
ReadOnly = true,
BackgroundColor = Color.White,
BorderStyle = BorderStyle.None,
SelectionMode = DataGridViewSelectionMode.FullRowSelect,
RowHeadersVisible = false,
AlternatingRowsDefaultCellStyle = new DataGridViewCellStyle
{
BackColor = Color.FromArgb(245, 249, 255)
},
ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle
{
BackColor = Color.FromArgb(65, 105, 225),
ForeColor = Color.White,
Font = new Font("Segoe UI", 10, FontStyle.Bold)
}
};
// 列定义
dgvWords.Columns.AddRange(
new DataGridViewTextBoxColumn { HeaderText = "单词", DataPropertyName = "WordText", Width = 150 },
new DataGridViewTextBoxColumn { HeaderText = "释义", DataPropertyName = "Meaning", Width = 250 },
new DataGridViewTextBoxColumn { HeaderText = "例句", DataPropertyName = "Example", Width = 350 }
);
mainPanel.Controls.Add(dgvWords);
// 绑定数据源
_bindingSource.DataSource = new BindingList<Word>();
dgvWords.DataSource = _bindingSource;
// 状态栏
StatusStrip statusStrip = new StatusStrip
{
Dock = DockStyle.Bottom,
BackColor = Color.FromArgb(65, 105, 225),
ForeColor = Color.White
};
ToolStripStatusLabel statusLabel = new ToolStripStatusLabel
{
Text = "就绪",
ForeColor = Color.White
};
statusStrip.Items.Add(statusLabel);
this.Controls.Add(statusStrip);
}
private void InitializeDataGridView()
{
// 已在上面的InitializeComponent中配置
}
private void LoadAllWords()
{
try
{
var words = _repository.GetAllWords();
_bindingSource.DataSource = new BindingList<Word>(words);
UpdateStatus($"已加载 {words.Count} 个单词");
}
catch (Exception ex)
{
MessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpdateStatus(string message)
{
if (this.Controls.OfType<StatusStrip>().FirstOrDefault() is StatusStrip statusStrip)
{
if (statusStrip.Items[0] is ToolStripStatusLabel statusLabel)
{
statusLabel.Text = message;
}
}
}
private void Button_Click(object sender, EventArgs e)
{
var btn = (Button)sender;
try
{
switch (btn.Name)
{
case "btnAdd":
if (string.IsNullOrWhiteSpace(txtWord.Text))
{
MessageBox.Show("单词不能为空", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtWord.Focus();
return;
}
_repository.AddWord(txtWord.Text, txtMeaning.Text, txtExample.Text);
LoadAllWords();
UpdateStatus("单词添加成功");
ClearInputs();
break;
case "btnDelete":
if (dgvWords.SelectedRows.Count == 0)
{
MessageBox.Show("请选择一个单词进行删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
var selectedWord = (Word)dgvWords.SelectedRows[0].DataBoundItem;
_repository.DeleteWord(selectedWord.WordText);
LoadAllWords();
UpdateStatus("单词删除成功");
ClearInputs();
break;
case "btnUpdate":
if (string.IsNullOrWhiteSpace(txtWord.Text))
{
MessageBox.Show("请先查询要修改的单词", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
_repository.UpdateWord(txtWord.Text, txtMeaning.Text, txtExample.Text);
LoadAllWords();
UpdateStatus("单词修改成功");
break;
case "btnSearch":
if (string.IsNullOrWhiteSpace(txtWord.Text))
{
LoadAllWords();
UpdateStatus("显示所有单词");
return;
}
var word = _repository.GetWord(txtWord.Text);
if (word != null)
{
txtMeaning.Text = word.Meaning;
txtExample.Text = word.Example;
UpdateStatus($"找到单词: {word.WordText}");
}
else
{
MessageBox.Show("未找到该单词", "查询结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
UpdateStatus($"未找到: {txtWord.Text}");
}
break;
case "btnTest":
var words = _repository.GetAllWords();
if (words.Count < 10)
{
MessageBox.Show("至少需要10个单词才能开始测试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
new TestForm(words).ShowDialog();
UpdateStatus("测试完成");
break;
}
}
catch (Exception ex)
{
MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
UpdateStatus($"错误: {ex.Message}");
}
}
private void ClearInputs()
{
txtWord.Clear();
txtMeaning.Clear();
txtExample.Clear();
}
}
// 数据库操作类
public class WordRepository
{
private readonly string _connStr;
// 添加构造函数初始化连接字符串
public WordRepository()
{
// 从配置文件读取连接字符串(需确保App.config中有配置)
_connStr = ConfigurationManager.ConnectionStrings["VocabularyDBConnection"].ConnectionString;
// 或者使用硬编码的连接字符串(测试用)
// _connStr = @"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;";
InitializeDatabase(); // 确保数据库和表存在
}
private void InitializeDatabase()
{
try
{
using (var conn = new SqlConnection(_connStr)) // 使用已初始化的字段
{
conn.Open();
// 创建数据库
var createDbCmd = new SqlCommand(
"IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'VocabularyDB') " +
"CREATE DATABASE VocabularyDB", conn);
createDbCmd.ExecuteNonQuery();
// 使用数据库
var useDbCmd = new SqlCommand("USE VocabularyDB", conn);
useDbCmd.ExecuteNonQuery();
// 创建表
var createTableCmd = new SqlCommand(
"IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Words') " +
"CREATE TABLE Words (" +
"WordText NVARCHAR(100) PRIMARY KEY, " +
"Meaning NVARCHAR(500) NOT NULL, " +
"Example NVARCHAR(1000))", conn);
createTableCmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show($"数据库初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// 以下方法保持原有逻辑,只需确保使用已声明的_connStr字段
public List<Word> GetAllWords()
{
var words = new List<Word>();
try
{
using (var conn = new SqlConnection(_connStr))
{
conn.Open();
var cmd = new SqlCommand("SELECT * FROM VocabularyDB.dbo.Words", conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
words.Add(new Word
{
WordText = reader["WordText"].ToString(),
Meaning = reader["Meaning"].ToString(),
Example = reader["Example"].ToString()
});
}
}
}
}
catch (Exception ex)
{
throw new Exception("获取单词列表失败: " + ex.Message);
}
return words;
}
public void AddWord(string word, string meaning, string example)
{
try
{
using (var conn = new SqlConnection(_connStr))
{
conn.Open();
var cmd = new SqlCommand(
"INSERT INTO VocabularyDB.dbo.Words (WordText, Meaning, Example) " +
"VALUES (@word, @meaning, @example)", conn);
cmd.Parameters.AddWithValue("@word", word);
cmd.Parameters.AddWithValue("@meaning", meaning);
cmd.Parameters.AddWithValue("@example", example);
cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Number == 2627) // 主键冲突
{
throw new Exception("该单词已存在");
}
throw new Exception("添加单词失败: " + ex.Message);
}
}
public void DeleteWord(string wordText)
{
try
{
using (var conn = new SqlConnection(_connStr))
{
conn.Open();
var cmd = new SqlCommand(
"DELETE FROM VocabularyDB.dbo.Words WHERE WordText = @word", conn);
cmd.Parameters.AddWithValue("@word", wordText);
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 0)
{
throw new Exception("未找到要删除的单词");
}
}
}
catch (Exception ex)
{
throw new Exception("删除单词失败: " + ex.Message);
}
}
public void UpdateWord(string wordText, string meaning, string example)
{
try
{
using (var conn = new SqlConnection(_connStr))
{
conn.Open();
var cmd = new SqlCommand(
"UPDATE VocabularyDB.dbo.Words " +
"SET Meaning = @meaning, Example = @example " +
"WHERE WordText = @word", conn);
cmd.Parameters.AddWithValue("@word", wordText);
cmd.Parameters.AddWithValue("@meaning", meaning);
cmd.Parameters.AddWithValue("@example", example);
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 0)
{
throw new Exception("未找到要更新的单词");
}
}
}
catch (Exception ex)
{
throw new Exception("更新单词失败: " + ex.Message);
}
}
public Word GetWord(string wordText)
{
try
{
using (var conn = new SqlConnection(_connStr))
{
conn.Open();
var cmd = new SqlCommand(
"SELECT * FROM VocabularyDB.dbo.Words WHERE WordText = @word", conn);
cmd.Parameters.AddWithValue("@word", wordText);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
return new Word
{
WordText = reader["WordText"].ToString(),
Meaning = reader["Meaning"].ToString(),
Example = reader["Example"].ToString()
};
}
}
}
return null;
}
catch (Exception ex)
{
throw new Exception("查询单词失败: " + ex.Message);
}
}
}
// 数据模型
public class Word
{
public string WordText { get; set; }
public string Meaning { get; set; }
public string Example { get; set; }
}
// 测试窗体
public partial class TestForm : Form
{
private readonly List<Word> _words;
private List<Word> _testWords;
private int _currentIndex;
private int _correctCount;
private readonly Random _random = new Random();
private bool _isMeaningToWord;
// 控件声明
private Label lblQuestion;
private Label lblPrompt;
private TextBox txtAnswer;
private Button btnSubmit;
private Button btnClose;
private Button btnRestart;
private Label lblFeedback;
private Label lblProgress;
private Timer timerFeedback;
public TestForm(List<Word> words)
{
_words = words;
InitializeComponent();
StartTest();
SetupUI();
}
private void InitializeComponent()
{
// 窗体设置
this.Size = new Size(600, 400);
this.StartPosition = FormStartPosition.CenterParent;
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Text = "单词测试";
// 主面板
Panel mainPanel = new Panel
{
Dock = DockStyle.Fill,
BackColor = Color.FromArgb(245, 249, 252),
Padding = new Padding(20)
};
this.Controls.Add(mainPanel);
// 问题标签
lblQuestion = new Label
{
Location = new Point(20, 20),
Size = new Size(550, 50),
Font = new Font("Segoe UI", 14, FontStyle.Bold),
ForeColor = Color.FromArgb(65, 105, 225)
};
mainPanel.Controls.Add(lblQuestion);
// 提示标签
lblPrompt = new Label
{
Location = new Point(20, 80),
Size = new Size(550, 25),
Font = new Font("Segoe UI", 10)
};
mainPanel.Controls.Add(lblPrompt);
// 答案文本框
txtAnswer = new TextBox
{
Location = new Point(20, 110),
Size = new Size(550, 35),
Font = new Font("Segoe UI", 12)
};
mainPanel.Controls.Add(txtAnswer);
// 提交按钮
btnSubmit = new Button
{
Text = "提交",
Location = new Point(20, 160),
Size = new Size(100, 35),
BackColor = Color.FromArgb(65, 105, 225),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
FlatAppearance = { BorderSize = 0 },
Font = new Font("Segoe UI", 10, FontStyle.Bold)
};
btnSubmit.Click += btnSubmit_Click;
mainPanel.Controls.Add(btnSubmit);
// 反馈标签
lblFeedback = new Label
{
Location = new Point(20, 210),
Size = new Size(550, 30),
Font = new Font("Segoe UI", 12, FontStyle.Bold)
};
mainPanel.Controls.Add(lblFeedback);
// 进度标签
lblProgress = new Label
{
Location = new Point(20, 250),
Size = new Size(200, 25),
Font = new Font("Segoe UI", 10)
};
mainPanel.Controls.Add(lblProgress);
// 重新开始按钮
btnRestart = new Button
{
Text = "重新开始",
Location = new Point(20, 280),
Size = new Size(120, 35),
BackColor = Color.FromArgb(60, 179, 113),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
FlatAppearance = { BorderSize = 0 },
Font = new Font("Segoe UI", 10, FontStyle.Bold),
Visible = false
};
btnRestart.Click += btnRestart_Click;
mainPanel.Controls.Add(btnRestart);
// 关闭按钮
btnClose = new Button
{
Text = "关闭",
Location = new Point(450, 280),
Size = new Size(120, 35),
BackColor = Color.FromArgb(220, 80, 60),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
FlatAppearance = { BorderSize = 0 },
Font = new Font("Segoe UI", 10, FontStyle.Bold)
};
btnClose.Click += btnClose_Click;
mainPanel.Controls.Add(btnClose);
// 计时器
timerFeedback = new Timer
{
Interval = 1500
};
timerFeedback.Tick += timerFeedback_Tick;
}
private void SetupUI()
{
// 设置样式
this.BackColor = Color.FromArgb(245, 249, 252);
}
private void StartTest()
{
// 随机选择20个单词进行测试
_testWords = _words.OrderBy(x => _random.Next()).Take(20).ToList();
_currentIndex = 0;
_correctCount = 0;
ShowNextWord();
}
private void ShowNextWord()
{
if (_currentIndex >= _testWords.Count)
{
lblQuestion.Text = $"测试完成! 正确率: {_correctCount}/{_testWords.Count}";
txtAnswer.Visible = false;
btnSubmit.Visible = false;
btnRestart.Visible = true;
lblFeedback.Visible = false;
lblProgress.Visible = false;
return;
}
// 随机选择测试方向(单词->释义 或 释义->单词)
_isMeaningToWord = _random.Next(2) == 0;
if (_isMeaningToWord)
{
lblQuestion.Text = $"释义: {_testWords[_currentIndex].Meaning}";
lblPrompt.Text = "请输入对应的单词:";
}
else
{
lblQuestion.Text = $"单词: {_testWords[_currentIndex].WordText}";
lblPrompt.Text = "请输入对应的释义:";
}
txtAnswer.Clear();
txtAnswer.Focus();
lblProgress.Text = $"进度: {_currentIndex + 1}/{_testWords.Count}";
lblFeedback.Visible = false;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string answer = txtAnswer.Text.Trim();
string correctAnswer = _isMeaningToWord ?
_testWords[_currentIndex].WordText :
_testWords[_currentIndex].Meaning;
if (answer.Equals(correctAnswer, StringComparison.OrdinalIgnoreCase))
{
_correctCount++;
lblFeedback.Text = "✓ 正确!";
lblFeedback.ForeColor = Color.Green;
}
else
{
lblFeedback.Text = $"✗ 错误! 正确答案: {correctAnswer}";
lblFeedback.ForeColor = Color.Red;
}
_currentIndex++;
lblFeedback.Visible = true;
timerFeedback.Start();
}
private void timerFeedback_Tick(object sender, EventArgs e)
{
lblFeedback.Visible = false;
timerFeedback.Stop();
ShowNextWord();
}
private void btnRestart_Click(object sender, EventArgs e)
{
txtAnswer.Visible = true;
btnSubmit.Visible = true;
btnRestart.Visible = false;
lblProgress.Visible = true;
StartTest();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
// 程序入口
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}在“WordRepository._connStr”和“WordRepository._connStr”之间具有二义性,请修改