从数据库检索数据时出错(ado.net)

时间:2013-03-12 04:44:24

标签: c# ado.net

从子行检索数据时出现错误。基本上我需要来自lecturerName的{​​{1}} tbl_lecturerprojectTitle来自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

请帮忙。

1 个答案:

答案 0 :(得分: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_project成为tbl_lecturer_project的父级,这样您就可以在其上调用GetChildRows