I am working on a C# application on Adding Admin to the database. I can select a data row from a grid, and the details of the selected row are displayed in textboxes for editing. However, when I change the textboxes and click the “Update” button, I receive the error message: “Select a record to update” even though I have already selected a row and the details are displayed correctly in the form. My SQL server works properly.
**This is a code of my updating and row selection **
private void adminview_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex != -1 && e.ColumnIndex != -1) { mobile = Convert.ToInt32(adminview.Rows[e.RowIndex].Cells[4].Value);
} else { MessageBox.Show("Invalid cell selected."); }
if (e.RowIndex >= 0)
{
DataGridViewRow row = adminview.Rows[e.RowIndex];
aname.Text = row.Cells["username"].Value.ToString();
amobile.Text = row.Cells["mobile"].Value.ToString();
adate.Value = Convert.ToDateTime(row.Cells["birth"].Value);
pw.Text = row.Cells["password"].Value.ToString();
if (row.Cells["gender"].Value.ToString() == "Male")
{
amale.Checked = true;
afemale.Checked = false;
}
else if (row.Cells["gender"].Value.ToString() == "Female")
{
afemale.Checked = true;
amale.Checked = false;
}
}
}
private void update_Click(object sender, EventArgs e)
{
if (adminview.SelectedRows.Count > 0)
{
name = aname.Text;
mobile = Convert.ToInt32(amobile.Text);
dob = adate.Value.ToString("yyyy-MM-dd");
passw = pw.Text;
if (amale.Checked == true)
{
gender = "Male";
}
else if (afemale.Checked == true)
{
gender = "Female";
}
conn.Open();
SqlCommand cmd = new SqlCommand("UPDATE admin SET name = '" + name + "', password = '" + passw + "', gender = '" + gender + "', birth = '" + dob + "' WHERE mobile = '" + mobile + "'", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Details Updated");
conn.Close();
Display(); //data show in grid
}
else
{
MessageBox.Show("Select a record to update.");
}
}
I expect to update my data in the database and row select in the grid correctly.
1