1

寻求朋友的帮助

我已经从数据库加载了 3 个表来DataSet使用DataReader,但我无法将它绑定到GridView.

protected void GetStudReport(Object o, EventArgs e)
{
    if (mycon.State != ConnectionState.Open)
    {
        List<string> lstQstn = new List<string>();

        mycon.Open();
        cmd = new MySqlCommand("SELECT * from scord_mark_table where stu_ID=@StID", mycon);
        cmd.Parameters.Add(new MySqlParameter("StID", MySqlDbType.VarChar, 10, "stu_ID"));
        cmd.Parameters["@StID"].Value = drpDnSearch3.SelectedValue;
        MySqlDataReader rdr1 = cmd.ExecuteReader();
        DataSet ds = new DataSet();
        DataTable dtScrTbl = new DataTable("ScoreTable");
        dtScrTbl.Load(rdr1);
        ds.Tables.Add(dtScrTbl);
        rdr1.Close();
        cmd = null;

        int i = 0;
        Dictionary<string, string> dctSub = new Dictionary<string, string>();
        using (DataTableReader dtr = ds.CreateDataReader())
        {
            while (dtr.Read())
            {
                lstQstn.Add(dtr["test_id"].ToString());

                while (i <= lstQstn.Count())
                {
                    cmd = new MySqlCommand("SELECT test_id,subject_id from qution_no_table where test_id='" + lstQstn[i].ToString() + "'", mycon);
                    MySqlDataReader rdr2 = cmd.ExecuteReader();
                    while (rdr2.Read())
                    {
                      dctSub.Add(rdr2["subject_id"].ToString(),rdr2["test_id"].ToString());
                    }
                    rdr2.Close();
                    break;
                }

                i++;


            }
            cmd = null;
        }

        string strTestID="where test_id='";
        i=0;
        foreach (string lst in lstQstn)
        {
            if (i > 0)
            {
                strTestID += @" and test_id='";
            }
            strTestID += lst + @"'";
            i++;
        }


        cmd = new MySqlCommand("SELECT * from qution_no_table " +strTestID+";"+"SELECT * from out_of_mark_table " +strTestID, mycon);

        MySqlDataReader rdr3 = cmd.ExecuteReader();

        DataTable dtQNoTbl = new DataTable("QstNoTable");
        dtQNoTbl.Load(rdr3);
        ds.Tables.Add(dtQNoTbl);

        rdr3.NextResult();

        // bind the second resultset
        DataTable dtOutMrkTbl = new DataTable("OutOfMarkTable");
        dtOutMrkTbl.Load(rdr3);
        ds.Tables.Add(dtOutMrkTbl);
        rdr3.Close();

        //**
        GridView1.DataSource = ds.Tables["OutOfMarkTable"];
        GridView1.DataBind(); //**
     }
}
4

1 回答 1

2

原因是您rdr3.NextResult()将读者推进到下一个结果(如果有的话)。但这已经在DataTable.Load. 来自 MSDN:

Load 方法使用来自已加载 IDataReader 的第一个结果集,并在成功完成后将读取器的位置设置为下一个结果集(如果有)。

所以你只需要省略它。另一种选择是使用 DatSet.Load(reader)一次添加最后两个表:

ds.Load(rdr, LoadOption.OverwriteChanges, "QstNoTable","OutOfMarkTable");
GridView1.DataSource = ds.Tables["OutOfMarkTable"]; 

DataSet.Load不会删除DataSet.

于 2012-11-03T00:00:07.397 回答