C#窗体,编写代码实现功能:用户还可以添加新课程,录入新课程的成绩,并把当前录入的成绩添加到数据库中。
时间: 2024-12-30 13:39:33 浏览: 25
在C#中,你可以使用Windows Forms(WPF)或ASP.NET MVC(Web应用程序)来实现这个功能。这里是一个简单的Windows Form应用程序的代码示例,用于添加新课程和成绩到数据库:
首先,你需要安装`System.Data.SqlClient`命名空间,它包含了处理SQL Server数据库的操作类。
```csharp
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
public partial class MainForm : Form
{
private SqlConnection dbConnection = new SqlConnection("your_connection_string_here");
public MainForm()
{
InitializeComponent();
// 连接到数据库
dbConnection.Open();
}
private void btnAddCourse_Click(object sender, EventArgs e)
{
string courseName = txtCourseName.Text;
if (!string.IsNullOrEmpty(courseName))
{
using (SqlCommand command = new SqlCommand($"INSERT INTO Courses (course_id, course_name) VALUES ('{Guid.NewGuid()}', '{courseName}')", dbConnection))
{
int result = command.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("新课程已成功添加!");
}
}
}
private void btnAddGrade_Click(object sender, EventArgs e)
{
string studentId = txtStudentId.Text;
string courseId = txtCourseId.Text;
double grade = Convert.ToDouble(txtGrade.Text);
if (!string.IsNullOrEmpty(studentId) && !string.IsNullOrEmpty(courseId) && grade != 0)
{
using (SqlCommand command = new SqlCommand(
$"INSERT INTO StudentGrades (student_id, course_id, score) VALUES ('{studentId}', '{courseId}', {grade})", dbConnection))
{
int result = command.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("成绩已成功添加到数据库!");
}
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
dbConnection.Close(); // 关闭数据库连接
}
}
```
在这个例子中,用户输入框分别对应课程名(txtCourseName)、学生ID(txtStudentId)和成绩(txtGrade)。点击"添加课程"按钮会将课程信息插入到Courses表,点击"添加成绩"按钮则会将成绩加入到StudentGrades表。
注意替换`your_connection_string_here`为实际的数据库连接字符串,格式通常是`Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;`.
阅读全文
相关推荐


















