简体   繁体   中英

Inserting 1 or 0 in Bit field in sqlDatabase based on Checkbox checked in GridView

I have a gridview which has a Checkbox Template Field, I am using C# code and basically when the user checks all the Checkboxes in the datagrid view I want to add a 1 or 0 into an SQL database with a datatype field Bit based on the checkbox being checked or not. Here is my code so far;

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;

I am struggling to implement this part of my project and any help would be much appreciated! Thanks in advance...

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM