如何将完整数据集从另一个类传递给Form?

时间:2013-12-26 03:05:27

标签: c#

我希望在类中单独读取数据进程,并将该数据传递给Form,以在DataGridView中显示为数据源。我可以在List中逐行构建,然后将其传递给Form,但我想知道是否有简单的方法将完整的数据集作为参数传递给表单?

以下是构建数据集的代码:

class DAL_ProjectMaster
{
    // List<string> ProjectList = new List<string>();
    OleDbConnection DBcon;
    OleDbCommand DBcmd;
    OleDbDataAdapter DBadp;
    ConString constr = new ConString();
    public void GetProjectMaster()
    {
        string connectString = constr.GetConString();

        DBcon = new OleDbConnection(connectString);
        DBcmd = new OleDbCommand("select * from ProjectMaster", DBcon);
        DBcon.Open();
        DBadp = new OleDbDataAdapter(DBcmd);
        DataSet ds = new DataSet();
        DBadp.Fill(ds);
       }
    }
}

我想将ds传递给Form,我可以将其用作DataGridview的数据源,如下所示:

      dataGridView1.DataSource = ds.Tables[0];

2 个答案:

答案 0 :(得分:0)

更改GetProjectMaster以返回DataSet

public DataSet GetProjectMaster()
{
    DataSet ds = new DataSet();
    string connectString = constr.GetConString();
    using( var con = new OleDbConnection(connectString))
    using( var cmd = new OleDbCommand("select * from ProjectMaster", con))
    {
        con.Open();
        using(var adp = new OleDbDataAdapter(cmd))
        {
            adp.Fill(ds);
        }
    }
    return ds;
}

现在您可以将上述方法称为

DAL_ProjectMaster dal = new DAL_ProjectMaster();
dataGridView1.DataSource = dal.GetProjectMaster().Tables[0];

答案 1 :(得分:0)

您可以使用会话 //用于分配

  DataSet ds = new DataSet();
    Session.Add("Name", ds);
    // for retrieve
    ds = (DataSet)Session["Name"];