SelectedRow计数在一种方法上始终等于0,但在另一种方法上效果很好

时间:2019-07-16 08:26:48

标签: c# datagridview

我正在从事创建客户和约会应用程序的项目。 我有一个datagridview从数据库中提取数据(工作正常),并允许我添加/删除/更新约会。 我将datagridview设置为FullRowSelect,并将MultiSelect设置为false,因此用户只能选择一行。 选择一行后,可以从数据库中更新或删除该行(和记录)。

选择一行后,单击删除,它会要求您确认,然后删除该行:

    private void deleteAppointmentButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this appointment?", "delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                MySqlConnection c = new MySqlConnection(SqlUpdater.conString);
                MySqlCommand delcmd = new MySqlCommand();

                if (appointmentCalendar.SelectedRows.Count != 0)
                {
                    delcmd.Connection = c;
                    c.Open();
                    delcmd.CommandText = "DELETE FROM appointment WHERE 
                    appointmentId = " + 
                    appointmentCalendar.CurrentRow.Cells[5].Value + ";";
                    delcmd.ExecuteNonQuery();
                    c.Close();
                    appointmentCalendar.Rows.RemoveAt(appointmentCalendar.CurrentRow.Index);
                    MessageBox.Show("Appointment Deleted");
                }

当我尝试更新一行时,使用:

   private void updateAppointmentButton_Click(object sender, EventArgs e)
        {

            if (appointmentCalendar.SelectedRows.Count != 0)
            {
                MessageBox.Show("Please select a row to update");
            }
            else
            {

                UpdateAppointment updateAppointment = new UpdateAppointment();

                updateAppointment.customerIdBox.Text = appointmentCalendar.CurrentRow.Cells[0].Value.ToString();
                updateAppointment.customerNameBox.Text = appointmentCalendar.CurrentRow.Cells[1].Value.ToString();
                updateAppointment.typeBox.Text = appointmentCalendar.CurrentRow.Cells[2].Value.ToString();
                updateAppointment.startTimeBox.Value = Convert.ToDateTime(appointmentCalendar.CurrentRow.Cells[4].Value.ToString());
                updateAppointment.endTimeBox.Value = Convert.ToDateTime(appointmentCalendar.CurrentRow.Cells[3].Value.ToString());

                updateAppointment.Show();
            }                            
        }

总是返回“请选择要更新的行”消息框,好像在按下按钮时行数为零。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

正如Serg所指出的,我使用的是!=(不等于)而不是==(等于)。

谢谢!