日期:2011-03-20 浏览次数:20443 次
程序可以直接拿来使用,运行通过。
----------------------------------------------------
testconstraint.aspx
----------------------------------------------------
<%@ Page Language="c#" debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<script language="c#" runat="server">
public DataSet ds;
void Page_Load(Object sender,EventArgs e)
{
if(!IsPostBack)
{
SqlConnection myConnection = new SqlConnection("server=(local);database=northwind;Trusted_Connection=yes");
SqlDataAdapter myDataAdapter1=new SqlDataAdapter("select * from suppliers",myConnection);
SqlDataAdapter myDataAdapter2=new SqlDataAdapter("select * from products",myConnection);
ds=new DataSet();
myDataAdapter1.Fill(ds,"suppliers");
myDataAdapter2.Fill(ds,"products");
MyDataGrid.DataSource=ds.Tables["suppliers"].DefaultView;
MyDataGrid.DataBind();
MyDataGrid2.DataSource=ds.Tables["products"].DefaultView;
MyDataGrid2.DataBind();
}
}
void MyDataGrid_Delete(Object sender,DataGridCommandEventArgs e)
{
String conn="server=(local);database=northwind;Trusted_Connection=yes";
String selectCommandText1="select * from suppliers";
String selectCommandText2="select * from products";
SqlDataAdapter myDataAdapter1=new SqlDataAdapter();
myDataAdapter1.SelectCommand=new SqlCommand();
myDataAdapter1.SelectCommand.CommandText=selectCommandText1;
myDataAdapter1.SelectCommand.Connection=new SqlConnection(conn);
SqlDataAdapter myDataAdapter2=new SqlDataAdapter();
myDataAdapter2.SelectCommand=new SqlCommand();
myDataAdapter2.SelectCommand.CommandText=selectCommandText2;
myDataAdapter2.SelectCommand.Connection=new SqlConnection(conn);
ds=new DataSet();
myDataAdapter1.Fill(ds,"suppliers");
myDataAdapter2.Fill(ds,"products");
CreateConstraint();
int index=(int)e.Item.ItemIndex;
ds.Tables["suppliers"].Rows[index].Delete();
ds.Tables["suppliers"].AcceptChanges();
myDataAdapter1.Update(ds,"suppliers");
MyDataGrid.DataSource=ds.Tables["suppliers"].DefaultView;
MyDataGrid.DataBind();
MyDataGrid2.DataSource=ds.Tables["products"].DefaultView;
MyDataGrid2.DataBind();
}
void CreateConstraint()
{
DataColumn parentColumn,childColumn;
ForeignKeyConstraint myForeignKeyConstraint;
parentColumn = ds.Tables["suppliers"].Columns["supplierID"];
childColumn = ds.Tables["products"].Columns["supplierID"];
myForeignKeyConstraint = new ForeignKeyConstraint("SupplierForeignKeyConstraint", parentColumn, childColumn);
myForeignKeyConstraint.DeleteRule = Rule.Cascade ;
myForeignKeyConstraint.UpdateRule = Rule.Cascade ;