c# - 如果datagridview中的复选框被选中,它将保存到数据库,如果没有,它只会提示选择一行

标签 c# mysql

这是我的代码,但它总是提示您是否要添加行,即使它没有被选中。您认为问题出在哪里?

 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");
                }
            }
}

最佳答案

在当前的 if 语句周围放置一个 if 语句,以检查所选行的数量:

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

关于c# - 如果datagridview中的复选框被选中,它将保存到数据库,如果没有,它只会提示选择一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32613668/

相关文章:

mysql - 在 cygwin 上连接到远程 MySQL 服务器

mysql - 如何从现有余额中获取新的运行余额?

php - 自动从 mysql 数据库更新 xml feed,无需刷新页面

mysql - 当子查询匹配时更新表

c# - .Net Core (2.1) - Lambda 函数可以工作,而在 2.2 中却不行?

c# - 在 Stream 上应用正则表达式?

c# - 傻瓜式表单设计器

c# - 使用 C# 在 Datagridview 中绘制统计图

mysql - 删除 SQL 中自特定日期以来未订购的客户数据

c# - try 没有捕获 WebException