简体   繁体   中英

If the checkbox in the datagridview is checked, it will save to database and if not it will just prompt to select a row

this is my code but it always prompt if you want to add the rows even if it is not checked. what do you think is the problem?

 private void btn_add_Click(object sender, EventArgs e)
 {
      List<DataGridViewRow> selectedRows = 
        (from row in dg_students.Rows.Cast<DataGridViewRow>() 
              where Convert.ToBoolean(row.Cells[3].Value) == true
              select row).ToList();         

        if (MessageBox.Show(string.Format("Are you sure you want to add this student?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                foreach (DataGridViewRow row in selectedRows)
                {
                    try
                    {


                        MySqlConnection conn = new MySqlConnection(myconn);
                         string Query = "Insert into southpoint_school.classlist(schoolYear, yearLevel, sectionName, studentID, studentName, gender) values ('" + schoolyr + "','" + cmb_level.Text + "','" + comboBox2.Text + "','" + row.Cells[0].Value.ToString() + "','" + row.Cells[1].Value.ToString() + "','" + row.Cells[2].Value.ToString() + "')";
                        MySqlCommand cmd = new MySqlCommand(Query, conn);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    MessageBox.Show("Successfully Saved");
                }
            }
}

Put an if statement around your current if statement, that checks the number of selected rows:

if(selectedRows.Count >= 1)
{
    //Your if statement to run with the selected rows
}
else
{
    //Prompt user to select a row
{

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