【发布时间】:2020-10-26 16:20:50
【问题描述】:
我有 5 个表格。第 5 种形式让我更新数据库中的条目。问题是,一旦我完成了一个条目的编辑并单击 Update 按钮,数据库中的所有其他条目都将与编辑后的条目相同。例如,我将“Mark”的名字编辑为“John”。一旦我点击更新,我所有的其他条目也变成了“John”,并且 John 的 empno 和部门等信息也将应用于其他条目。我做错了什么?
代码:
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();
}
}
}
【问题讨论】:
-
您缺少指定
EmployeeID 的where子句(您应该有一个ID,而不是名称,才能将其单独列出,对吧?)。您应该真正使用参数,而不是连接字符串。此外,您不应存储 Connection 对象,而应就地声明它并将其与您创建的所有其他一次性对象一起丢弃。
标签: c# database winforms datagridview crud