我在更新从另一种形式的数据库中提取的数据网格视图上的选定行时遇到问题。我使用它将信息从数据网格视图获取到另一个窗体上的文本框中:
private void updateAppointmentButton_Click(object sender, EventArgs e)
{
UpdateAppointment updateAppointment = new UpdateAppointment();
updateAppointment.mainFormObject = this;
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();
MySqlConnection c = new MySqlConnection(SqlUpdater.conString);
MySqlCommand updateCmd = new MySqlCommand();
updateCmd.Connection = c;
c.Open();
updateCmd.CommandText = $"UPDATE customer SET customerName = '{customerNameBox.Text}'";
updateCmd.ExecuteNonQuery();
c.Close();
MessageBox.Show("Appointment Updated");
我认为这是SQL查询,但不确定如何将其限制为所选行上的信息。现在,它将更新数据网格视图和数据库上的每个人。
有什么想法吗?谢谢!
我试过把 MainForm.appointmentCalendar.CurrentRow.Cells[1].Value.ToString((;
作为 SQL 查询中的 WHERE,但它返回"需要对象引用"错误。
有一个具有唯一客户 ID 的列,那么在您的查询中您需要
Update customer SET customerName = '{customerNameBox.Text}' where customerID = 'UniqueID'
-----(无论您尝试更新的 ID 是什么(
大概是像int.Parse(otherDataGrid.selectedRows[0].Cells["ID"].Value.ToString())
@edit
我真的不明白你想说什么。您可能需要尝试使用参数。这将是您的查询:
Update appointment set type = @type, start = @start, end = @end where customerId = @id
然后在执行命令之前,您说:
updateCmd.Parameters.AddWithValue("@type", typeBox.Text);
并对所有其他参数执行此操作。还要确保您的文本框不为空,因为如果您的查询正在删除数据(也许它正在使用空字符串更新数据(,则很可能为空