这是我的代码,但它总是提示您是否要添加行,即使它没有被选中。您认为问题出在哪里?
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/