I have 5 forms. The 5th form lets me update an entry in a database. The problem is that once I'm finished editing with an entry and click on Update button, all of the other entries in the database will be the same as the edited entry. So for example, I edited the first name of "Mark" to "John". Once I click on Update, all of my other entries also become "John" and John's info like empno and department are also applied to the other entries. What did I do wrong?
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace OOP_Draft
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
InitDataGrid();
}
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Kim\Documents\SMEMCO.mdf;Integrated Security=True");
private void Form5_Load(object sender, EventArgs e)
{
}
private void dgvUpdate_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void InitDataGrid()
{
con.Open();
var da = new SqlDataAdapter("SELECT * FROM LoanRecord", con);
var dtbl = new DataTable();
da.Fill(dtbl);
dgvUpdate.DataSource = dtbl;
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("delete from LoanRecord where EmployeeName ='"+txtName.Text+"'", con);
cmd.ExecuteNonQuery();
con.Close();
InitDataGrid();
MessageBox.Show("Data sucessfully deleted to database.");
}
private void btnUpdate_Click(object sender, EventArgs e)
{
string query = "UPDATE LoanRecord SET EmployeeName ='"+txtName.Text+"',EmployeeNumber='"+txtEmpno.Text+"',Department='"+txtDept.Text+"',LoanAmount='"+txtAmount.Text+"',YearsToPay='"+txtYears.Text+"',MonthlyPayment='"+txtMonth.Text+"',TotalPayment='"+txtOverall.Text+"'";
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.SelectCommand.ExecuteNonQuery();
con.Close();
InitDataGrid();
MessageBox.Show("Data sucessfully updated to database.");
}
private void dgvUpdate_MouseDoubleClick(object sender, MouseEventArgs e)
{
txtName.Text = dgvUpdate.SelectedRows[0].Cells[1].Value.ToString();
txtEmpno.Text = dgvUpdate.SelectedRows[0].Cells[2].Value.ToString();
txtDept.Text = dgvUpdate.SelectedRows[0].Cells[3].Value.ToString();
txtAmount.Text = dgvUpdate.SelectedRows[0].Cells[4].Value.ToString();
txtYears.Text = dgvUpdate.SelectedRows[0].Cells[5].Value.ToString();
txtMonth.Text = dgvUpdate.SelectedRows[0].Cells[6].Value.ToString();
txtOverall.Text = dgvUpdate.SelectedRows[0].Cells[7].Value.ToString();
}
private void btnReset_Click(object sender, EventArgs e)
{
txtName.Clear();
txtEmpno.Clear();
txtEmail.Clear();
txtDept.Clear();
txtAmount.Clear();
txtYears.Clear();
txtMonth.Clear();
txtOverall.Clear();
}
}
}