[英]Error when retrieving data from database (ado.net)
从子行检索数据时出现错误。 基本上,我需要tbl_lecturer
的lecturerName
tbl_lecturer
, projectTitle
的tbl_lecturer_project
。
这是我的代码。
//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要求其表为
tbl_lecturer_project
的行,但指定行的表为tbl_allocated_project
。
请帮忙。
应该这样:
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_project
成为tbl_allocated_project
的父tbl_lecturer_project
,这应该允许您对其调用GetChildRows
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.