[英]How save DataGridViewComboBoxColumn in SQL Server database using C#
I am going to develop school management system and want to save attendance record in database from DataGridViewComboBoxColumn each student in class with Save button.我将开发学校管理系统,并希望使用保存按钮将 class 中每个学生的出勤记录保存在数据库中。
I means set all student record eg present, absent or leave the save record in database when the "save" button is pressed.我的意思是当按下“保存”按钮时设置所有学生记录,例如存在、缺席或将保存记录留在数据库中。
This is my code - it works when I change cell of 1st student这是我的代码 - 当我更改第一个学生的单元格时它可以工作
private void AttendanceDataGridVies_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
AttendanceDataGridVies.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void AttendanceDataGridVies_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
string comboboxSelectedValue = string.Empty;
if (AttendanceDataGridVies.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewComboBoxColumn))
{
comboboxSelectedValue = AttendanceDataGridVies.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
label2.Text = comboboxSelectedValue;
}
}
You probably want to set up something like Entity Framework to handle the database functions.您可能想要设置类似 Entity Framework 的东西来处理数据库功能。 This article is several years old now, but I think it can probably get you on your way: Entity-Framework-Tutorial-for-Beginners这篇文章已经有好几年了,但我认为它可能会让你上路: Entity-Framework-Tutorial-for-Beginners
Also, typically, you would want to separate the DB layer from your presentation layer.此外,通常,您希望将 DB 层与表示层分开。 However, you can set up your own connection strings and write your own SQL instead, if you would like.但是,如果您愿意,您可以设置自己的连接字符串并编写自己的 SQL。 To do so, you basically need to:为此,您基本上需要:
A very simple example connecting to a local SQL MDF inside the project:一个非常简单的示例连接到项目内的本地 SQL MDF:
private void button1_Click(object sender, EventArgs e)
{
addToDatabase();
}
private void addToDatabase()
{
string connection = @"Server=(LocalDB)\MSSQLLocalDB;attachdbfilename=C:\Users\xxxxx\source\repos\MySolution\MyProject\MyDatabase.mdf;integrated security=True;";
SqlConnection sqlConnection = new SqlConnection(connection);
string query = "INSERT INTO Table1 " +
"(Id, Column1, Column2) " +
"VALUES (@Id, @Column1, @Column2) ";
SqlCommand cmd = new SqlCommand(query, sqlConnection);
cmd.Parameters.Add("@Id", SqlDbType.Int).Value = 1;
cmd.Parameters.Add("@Column1", SqlDbType.VarChar, 50).Value = "value1";
cmd.Parameters.Add("@Column2", SqlDbType.VarChar, 50).Value = "Value2";
try
{
sqlConnection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.