我正在尝试在 Visual Studio C# 中编写代码,其中我有 3 个表客户、产品、订单,所有这三个表都是相关的
现在我已经创建了 datagridview 并从数据库中获取值,当我编辑 datagrid 时,它也会更新数据库,但是当我尝试更新 Product_id 时,它是产品的主键和订单的外键。
它给出了错误
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection conn;
SqlDataAdapter da;
DataSet ds;
public Form1()
{
InitializeComponent();
conn = new SqlConnection("user id=sa;" +
"password=sa@123;server=sudhanshu-lappy;" +
"Trusted_Connection=yes;" +
"database=alpha; " +
"connection timeout=30");
try
{
conn.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
//DataTable dt = null;
//SqlCommand cmd = new SqlCommand("SELECT * FROM orders", conn);
//SqlDataReader reader = cmd.ExecuteReader();
//dt = new DataTable();
//dt.Load(reader);
//dataGridView1.DataSource = dt;
//DataGridViewButtonColumn clbt_delet = new DataGridViewButtonColumn();
//clbt_delet.HeaderText = "DELETE";
//clbt_delet.Text = "Delete";
//clbt_delet.UseColumnTextForButtonValue = true;
//dataGridView1.Columns.Add(clbt_delet);
//da = new SqlDataAdapter("select * from orders", conn);
//SqlCommandBuilder cb = new SqlCommandBuilder(da);
//ds = new DataSet();
//da.Fill(ds);
//dataGridView1.DataSource = ds.Tables[0];
//now u can save changes to back end with
}
private void button1_Click(object sender, EventArgs e)
{
da.Update(ds);
}
private void button2_Click(object sender, EventArgs e)
{
da.Update(ds);
}
private void button3_Click(object sender, EventArgs e)
{
da.Update(ds);
}
private void ordersToolStripMenuItem_Click(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from orders", conn);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void productToolStripMenuItem_Click(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from product", conn);
SqlCommandBuilder cb1 = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds);
dataGridView3.DataSource = ds.Tables[0];
}
private void customerToolStripMenuItem_Click(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from customer", conn);
SqlCommandBuilder cb2 = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds);
dataGridView2.DataSource = ds.Tables[0];
}
}
}
其次,我只能通过更新操作更新订单表,其他两个表不会发生
苏丹舒