【发布时间】:2014-03-05 21:22:00
【问题描述】:
我有一个 Medicalcentre 表和 windowadmin 表,它们使用 mcID 相互关联。我首先将medicalcentre 表中存在的mcType 和mcCentre 显示到gridview,然后使用外连接将windowsadmin 表中的winusername 字段和winPassword 字段显示到gridview。我想要实现的是使用删除功能删除一条记录。但是我得到了错误,请参见第三张图片。
我的 windowsadmin 和医疗中心表
我的 windowsadmin 和 medicalcentre 表关系
我的表单
我的错误
private void LoadMedicalCentreRecords()
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandText = "SELECT cen.mcid, mcType, mcCentre, win.winUsername, win.winPassword FROM MEDICALCENTRE AS cen";
strCommandText += " LEFT OUTER JOIN WINDOWSADMIN as win on cen.mcid = win.mcid";
MedicalCentreAdapter = new SqlDataAdapter(strCommandText, myConnect);
//command builder generates Select, update, delete and insert SQL
// statements for MedicalCentreAdapter
//SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(MedicalCentreAdapter);
// Empty Employee Table first
MedicalCentre.Clear();
// Fill Employee Table with data retrieved by data adapter
// using SELECT statement
MedicalCentreAdapter.Fill(MedicalCentre);
// if there are records, bind to Grid view & display
if (MedicalCentre.Rows.Count > 0)
grdMc.DataSource = MedicalCentre;
}
private int DeleteMedicalCentreRecord()
{
// no row in GridView selected
if (currentRow == null)
{
return 0;
}
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandText = "DELETE FROM WINDOWSADMIN WHERE winID=@WINID; DELETE FROM MEDICALCENTRE WHERE mcID=@MCID;";
SqlCommand deleteCmd = new SqlCommand(strCommandText, myConnect);
// Cell - contains employee ID
int winID = Convert.ToInt32(currentRow.Cells[0].Value);
int mcID = Convert.ToInt32(currentRow.Cells[0].Value);
deleteCmd.Parameters.AddWithValue("@WINID", winID);
deleteCmd.Parameters.AddWithValue("@MCID", mcID);
//// STEP 3: open connection and retrieve data by calling ExecuteReader
myConnect.Open();
//STEP 4: execute command
int result = deleteCmd.ExecuteNonQuery();
// STEP 5: Close
myConnect.Close();
return result;
}
【问题讨论】:
-
你那里碰巧有一个带有 ON DELETE RESTRICT 的外键吗?
-
我不这么认为,我如何检查它? erm 在我使用外连接之前,我只能从医疗中心表中删除字段,但是在与 windowsadmin 表进行外连接并为 windowsadmin 字段编写删除代码之后。错误出现了@Vlad Schnakovszki
-
能否展示创建 FK_WINDOWSADMIN_MEDICALCENTER 外键的 SQL 代码?
-
代码?我通过单击创建了关系。见第二张图片@Steve
-
好的,那是一样的。但是您确定当您删除一个 mcID 时,WindowsAdmin 表中没有更多具有该 mcID 的用户未被上一个查询删除吗?
标签: c# gridview outer-join