📄 14.4.txt
字号:
Listing 14.4 Foreign-Key Constraints
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace _13_ForeignKeyConstraints
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dgParent;
private System.Windows.Forms.DataGrid dgChild;
private System.Windows.Forms.ComboBox cbConstraints;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnSet;
private DataSet ds;
private ForeignKeyConstraint fkConstraint;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
// fill constraint combo
cbConstraints.Items.Add(“Cascade”);
cbConstraints.Items.Add(“SetNull”);
cbConstraints.Items.Add(“SetDefault”);
cbConstraints.Items.Add(“None”);
cbConstraints.SelectedIndex = 3;
// create tables
ds = new DataSet();
DataTable parentTable = ds.Tables.Add( “ParentTable” );
DataTable childTable = ds.Tables.Add( “ChildTable” );
// create columns
parentTable.Columns.Add( “ID”, typeof(int) );
DataColumn linkedParent = parentTable.Columns.Add(
“LinkedID”, typeof(int) );
childTable.Columns.Add( “ID”, typeof(int) );
DataColumn linkedChild = childTable.Columns.Add(
“LinkedID”, typeof(int) );
// create the foreign key constraint and set to None
fkConstraint = new ForeignKeyConstraint( “LinkedIDFK”,
linkedParent, linkedChild );
fkConstraint.UpdateRule = Rule.None;
fkConstraint.DeleteRule = Rule.None;
// add constraint to child column
childTable.Constraints.Add( fkConstraint );
// data bind the 2 DataGrids
dgParent.SetDataBinding( ds, “ParentTable” );
dgChild.SetDataBinding( ds, “ChildTable” );
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
private void InitializeComponent()
{
// wizard generated code removed
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnSet_Click(object sender, System.EventArgs e)
{
// change the constraint based on ComboBox value
if( cbConstraints.SelectedItem == null )
return;
string constraintName = cbConstraints.Text;
if( constraintName == “None” )
{
fkConstraint.DeleteRule = Rule.None;
fkConstraint.UpdateRule = Rule.None;
}
else if( constraintName == “Cascade” )
{
fkConstraint.DeleteRule = Rule.Cascade;
fkConstraint.UpdateRule = Rule.Cascade;
}
else if( constraintName == “SetNull” )
{
fkConstraint.DeleteRule = Rule.SetNull;
fkConstraint.UpdateRule = Rule.SetNull;
}
else if (constraintName == “SetDefault” )
{
fkConstraint.DeleteRule = Rule.SetDefault;
fkConstraint.UpdateRule = Rule.SetDefault;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -