每当我保存gridview数据时,它会保存所有数据而不是插入的行
using (SqlConnection con = new SqlConnection(conn))
{
string query = "INSERT INTO dbo.[Ledger_" + tbpg.Text + "] VALUES(@Sno, @Date, @Particulars, @Credit, @Debit, @Balance)";
query += "DELETE FROM dbo.[Ledger_"+tbpg.Text+"] WHERE Date IS NULL;";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("@Sno", SqlDbType.Int).Value = row.Cells["Sno"].Value ?? (object)DBNull.Value;
cmd.Parameters.Add("@Date", SqlDbType.Date).Value = row.Cells["Date"].Value ?? (object)DBNull.Value;
cmd.Parameters.Add("@Particulars", SqlDbType.VarChar).Value = row.Cells["Particulars"].Value ?? (object)DBNull.Value;
cmd.Parameters.Add("@Credit", SqlDbType.Int).Value = row.Cells["Credit"].Value ?? (object)DBNull.Value;
cmd.Parameters.Add("@Debit", SqlDbType.Int).Value = row.Cells["Debit"].Value ?? (object)DBNull.Value;
cmd.Parameters.Add("@Balance", SqlDbType.Int).Value = row.Cells["Balance"].Value ?? (object)DBNull.Value;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
答案 0 :(得分:0)
//namespaces
public partial class Database_Manager : Form
{
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public Database_Manager()
{
InitializeComponent();
}
private void Database_Manager_Load(object sender, EventArgs e)
{
labeltitle.Text = "Select the table you want to edit.";
}
private void dbupdate()
{
try {
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("Update Successful!");
}
catch(Exception es)
{
MessageBox.Show(es.Message);
}
}
private void buttonupdate_Click(object sender, EventArgs e)
{
dbupdate();
}
上面的代码可以解决这个问题。您的代码会从datagridview中插入记录,因为您没有明确定义应该考虑哪一行,所以它可能会插入所有datagridview行。 我提供的代码可以查找现有行的更新,还可以插入新行