基于GridView中选中的复选框在sql数据库的位字段中插入1或0

时间:2011-04-21 13:05:40

标签: c# asp.net

我有一个gridview,它有一个Checkbox模板字段,我正在使用C#代码,基本上当用户检查datagrid视图中的所有Checkbox时,我想将1或0添加到SQL数据库中,数据类型字段基于Bit在被选中的复选框上。这是我到目前为止的代码;

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", SqlDbType.Bit).Value = AttendanceChecked;
                //command.Parameters.AddWithValue("@AttendanceChecked", CheckBox("Attend
                //com.Parameters.Add("@Approved", SqlDbType.Bit).Value = status;

我正在努力实施我的项目的这一部分,任何帮助将不胜感激!提前谢谢......

1 个答案:

答案 0 :(得分:0)

试试这个:

command.Parameters["@AttendanceChecked"].Value = AttendanceChecked ? 1 : 0;