【发布时间】:2021-06-28 22:45:30
【问题描述】:
我在数据库中有以下 2 个表:
-
Movies(id, title, year) 是表 Language 的父级 -
Language(movie_id, language) ----movie_id 参考Movies.id
我编写了以下代码,但我仍然需要执行更新/删除部分并在子表中添加新记录
- 当我从子项(语言)中选择一条记录时,我必须删除并更新一条记录
- 当我从父表(电影)中选择一条记录时,我必须在子表中添加一条新记录
代码:
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 lab1_v2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connectionString = "Server=DESKTOP-T33VBF8;Database=lab1SGBD_v6;Integrated Security=true";
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Open connection
connection.Open();
MessageBox.Show("State of the connection: " + connection.State.ToString());
// Create the data set
DataSet dataset = new DataSet();
// Create the two SQL Data Adapters for parent and child tables.
SqlDataAdapter parentAdapter = new SqlDataAdapter("SELECT * FROM Movies;", connection);
SqlDataAdapter childAdapter = new SqlDataAdapter("SELECT * FROM Languages;", connection);
// Create and populate the parent DataTable and the child DataTable
parentAdapter.Fill(dataset, "Movies");
childAdapter.Fill(dataset, "Languages");
// Create the two BindingSources for parent and child DataTable
BindingSource parentBS = new BindingSource();
BindingSource childBS = new BindingSource();
// Show all the records from parent DataTable in dataGridViewParent
parentBS.DataSource = dataset.Tables["Movies"];
dataGridViewParent.DataSource = parentBS;
// Create and add in the DataSet the DataRelation between parent DataTable and child DataTable
DataColumn parentPK = dataset.Tables["Movies"].Columns["id"];
DataColumn childFK = dataset.Tables["Languages"].Columns["movie_id"];
DataRelation relation = new DataRelation("fk_parent_child", parentPK, childFK);
dataset.Relations.Add(relation);
// Show in dataGridView the child records which are from the parent record selected
childBS.DataSource = parentBS;
childBS.DataMember = "fk_parent_child";
dataGridViewChild.DataSource = childBS;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
}
}
【问题讨论】:
-
I still have to do the following thingswhat is stopping you? -
删除/更新时不知道从哪里开始,如何开始
标签: c# .net sql-server visual-studio .net-framework-version