I am trying to edit a row from the datagridview. Every row has a button. When I press one of the rows button, a second form opens and show me the information in textboxes about that row and I need to edit what I want.
The problem is that I already wrote the code for editing but I can't add the DataGridViewCellEventArgs in the button function, or I can't use RowIndex to edit a specific row.
Here is the code:
public void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-VUPD668;Initial Catalog=dbApp;Integrated Security=True");
SqlCommand cmd;
cmd = new SqlCommand("UPDATE tableApplication SET Name='" + txtName.Text + "',Package='" + txtPackage.Text + "',Hour='" + txtHour.Text + "',Date='" + txtDate.Text + "',Phone='" + txtPhone.Text + "',Observations='" + txtObservations.Text + "' WHERE ID=" + f1.dgvContactList.Rows[rowIndex].Cells[0].Value.ToString(), conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Edit was saved");
this.Close();
}
and here is the code from the main form with the dgv
public void dgvContactList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 7)
{
formAddEditContact f2 = new formAddEditContact();
int rowIndex = e.RowIndex;
formContact f1 = new formContact();
f2.lblTitle.Text = "Edit";
f2.btnSave.Visible = false;
f2.btnUpdate.Visible = true;
f2.btnDelete.Visible = true;
f2.txtName.Text = f1.dgvContactList.Rows[rowIndex].Cells[1].Value.ToString();
f2.txtPackage.Text = f1.dgvContactList.Rows[rowIndex].Cells[2].Value.ToString();
f2.txtHour.Text = f1.dgvContactList.Rows[rowIndex].Cells[3].Value.ToString();
f2.txtDate.Text = f1.dgvContactList.Rows[rowIndex].Cells[4].Value.ToString();
f2.txtPhone.Text = f1.dgvContactList.Rows[rowIndex].Cells[5].Value.ToString();
f2.txtObservations.Text = f1.dgvContactList.Rows[rowIndex].Cells[6].Value.ToString();
f2.ShowDialog();
How I can use RowIndex in the button function. How I can add DataGridViewCellEventArgs.
formContact
f1
? The form is never shown, so the code …f1.dgvContactList.Rows[rowIndex].Cells[1].Value.ToString();
is not going to have any rows since the grid has not been displayed. Have you tried…dgvContactList.Rows[rowIndex].Cells[1].Value.ToString();
? – JohnG