将复选框模板字段中的值插入sql数据库字段类型Bit

本文关键字:字段 sql 插入 数据库 Bit 类型 复选框 | 更新日期: 2023-09-27 17:52:47

我有一个gridview,它有一个复选框模板字段,我使用c#代码,基本上当用户检查数据网格视图中的所有复选框时,我想将这些值添加到具有数据类型字段位的SQL数据库中。下面是我到目前为止的代码;

protected void SaveRegisterButton_Click(object sender, EventArgs e)
{
            SqlConnection connection;
            SqlCommand command;
            int numRowsAdded;
            int id;
            Boolean AttendanceChecked;
    foreach (GridViewRow row in GridView2.Rows)
    {
        if (((CheckBox)row.FindControl("AttendanceCheckBox")).Checked)
        {

            try
            {
                // Connecting to the database using the connection string in the web.config file
                connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
                // Create an INSERT Sql statement
                // To prevent an Sql injection attack, we add parameters with names starting with an @ symbol
                command = new SqlCommand("INSERT INTO Attendance(Present, StudentID, LessonID) VALUES(@AttendanceChecked, @StudentID, @LessonID)",

                // Replace the parameters with the actual values read from the form
                //command.Parameters.AddWithValue("AttendanceChecked", AttendanceCheckBox);

如何将复选框控件的值传递到数据类型为Bit的sql数据库字段中?任何帮助都很感激,提前感谢!

将复选框模板字段中的值插入sql数据库字段类型Bit

首先,如果没有找到复选框(例如,如果它是页眉/页脚),下面的代码将抛出空引用异常。

if (((CheckBox)row.FindControl("AttendanceCheckBox")).Checked)

唯一可以存储在位域中的是1或0,而复选框的"值"是文本。您是否真的希望根据值选择要保存到哪个字段,然后根据复选框是否被选中来选择要保存的值?请详细说明。

进一步更新尝试下面的代码:

foreach (GridViewRow row in GridView2.Rows)
    {
    CheckBox AttendanceCheckBox = row.FindControl("AttendanceCheckBox") as CheckBox;
    if (AttendanceCheckBox != null)
    {
       try
       {                
           connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
           SqlCommand command = new SqlCommand("INSERT INTO Attendance(Present, StudentID, LessonID) VALUES(@AttendanceChecked, @StudentID, @LessonID)");
           command.Parameters.AddWithValue("@AttendanceCheck",AttendanceCheckBox.Checked);

您还需要使用相同的command.Parameters.AddWithValue方法添加@StudentID和@LessonID的值。