2013-03-12 115 views
1

從子行檢索數據時出現錯誤。基本上我需要從tbl_lecturerlecturerName,projectTitletbl_lecturer_project從數據庫檢索數據時出錯(ado.net)

這是我的代碼。

//get data from 3 tables 
DataSet ds = new DataSet(); // .xsd file name 
DataTable dt = new DataTable(); 

//Connection string replace 'databaseservername' with your db server name 
SqlConnection con = new SqlConnection(connectionString); 
SqlCommand cmd = new SqlCommand(); 
SqlDataAdapter adapter; 

con.Open(); 

//Stored procedure calling. It is already in sample db. 
string selectSQL = "SELECT * FROM tbl_allocated_project where allocatedGroupId='" + team + "'"; 
cmd = new SqlCommand(selectSQL, con); 
ds = new DataSet(); 
adapter = new SqlDataAdapter(cmd); 
adapter.Fill(ds, "tbl_allocated_project"); 

cmd.CommandText = "SELECT * FROM tbl_lecturer_project"; 
adapter.Fill(ds, "tbl_lecturer_project"); 

cmd.CommandText = "SELECT * FROM tbl_lecturer"; 
adapter.Fill(ds, "tbl_lecturer"); 

DataRelation dr1 = new DataRelation("dr1", ds.Tables["tbl_lecturer"].Columns["lecturerId"],ds.Tables["tbl_lecturer_project"].Columns["lecturerId"]); 
DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], ds.Tables["tbl_allocated_project"].Columns["allocatedProjectId"]); 
ds.Relations.Add(dr1); 
ds.Relations.Add(dr2); 

foreach (DataRow row in ds.Tables["tbl_allocated_project"].Rows) 
{ 
    lblDisplay.Text = ""; 
    //lblDisplay.Text += row["allocatedGroupId"]; 
    //lblDisplay.Text += " " + row["intro"]; 

    foreach (DataRow col in row.GetChildRows(dr2)) 
    { 
     DataRow rowdata = col.GetParentRows(dr1)[0]; 
     //lblDisplay.Text += "  "; 
     lblDisplay.Text += rowdata["projectTitle"]; 
    } 
} 

我得到這個錯誤:

GetChildRows requires a row whose table is tbl_lecturer_project , but the specified row's table is tbl_allocated_project .

請幫助。

回答

0

應該這樣:

DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], ds.Tables["tbl_allocated_project"].Columns["allocatedProjectId"]); 

是這樣的:

DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_allocated_project"].Columns["lecturerProjectId"], ds.Tables["tbl_lecturer_project"].Columns["allocatedProjectId"]); 

這將使tbl_allocated_projecttbl_lecturer_project家長,應該使你可以調用GetChildRows就可以了。

相關問題