我有一个返回DataSet的方法。
protected DataSet GetProgramList()
{
DataSet ds1 = new DataSet();
using (SqlConnection cn = new SqlConnection("server=Daffodils-PC\\sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))
{
using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT * FROM Program", cn))
da.Fill(ds1, "Program");
}
return ds1;
}
我想在其他方法中使用DataSet中的特定列,如下所示:
protected DataSet GetStudentByProgramID(int programID)
{
DataSet ds2 = new DataSet();
using (SqlConnection cn = new SqlConnection("server=Daffodils-PC\\sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))
{
using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT LastName, FirstName FROM Student JOIN Program on Program.ProgramID = Student.ProgramID WHERE ProgramID ="+programID, cn))
da.Fill(ds2, "Student");
}
return ds2;
}
例如,我想使用第一个方法中程序表中的 ProgramID 列。我知道我必须将返回的数据集存储在变量中,但如何?
答案 0 :(得分:1)
鉴于您ds1
方法
GetStudentByProgramID
然后你可以这样使用它
rotected DataSet GetStudentByProgramID(int programID)
{
DataColumn programId = ds1.Tables[0].Columns["ProgramId"];
//to read row you can iterate from ds1.Table[0].Rows
DataSet ds2 = new DataSet();
using (SqlConnection cn = new SqlConnection("server=Daffodils-PC\\sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))
{
using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT LastName, FirstName FROM Student WHERE ProgramID ="+programID, cn))
da.Fill(ds2, "Student");
}
return ds2;
}
答案 1 :(得分:0)
为什么不写一个查询?
SELECT programID, LastName, FirstName
FROM Program JOIN Student ON Program.Id=Student.ProgramId
这样,你就会让每个学生都有他们的programID。