Fran Montserrat Fran Montserrat - 3 months ago 12
C# Question

C# How to create a Dataset instance with relations between two tables

0
down vote
favorite
well thats my problem. I'm trying to query a remote postgresql DB and then fill TWO RELATED instanced tables with the result, so i can fill a form that displays information for both tables. Doing this with a single table was simple, but now i'm unable to correctly define relationships. I'm getting the “Object reference not set to an instance of an object” error What im doing wrong?

Relation is "components/provider_id" to "provider/id" so i can fill provider fields automatically in the components forms (while doing a search query).

Heres my code:

OdbcDataAdapter sdata = new OdbcDataAdapter(//Query string whatever);
OdbcDataAdapter sdata2 = new OdbcDataAdapter(//Query string whatever);

DataSet ds = new DataSet(); //new dataset instance

DataTable dtbl = new DataTable(); //two new instanced tables
DataTable dtbl2 = new DataTable();

sdata.Fill(dtbl); //fill both tables with each query data
sdata2.Fill(dtbl2);

ds.Tables.Add(dtbl); //Add those tables to DataSet
ds.Tables.Add(dtbl2);

//So now im tring to create a relation between both tables
// im getting "“Object reference not set to an instance of an object”

DataRelation dr = new DataRelation("provcomp",
ds.Tables["dtbl"].Columns["id"],
ds.Tables["dtbl2"].Columns["id_prov_comp"]);


Also i suppose that after that i will need some advice on creating some keys for the columns.

Can i get a little help? Please keep in mind that im fairly new to programing in general and c# in particular.

Thanks in advance.

Answer
        DataSet ds = new DataSet(); //new dataset instance

        DataTable dtbl = new DataTable("Your Parent TableName");  //two new instanced tables
        DataTable dtbl2 = new DataTable("Your Child TableName");

        sdata.Fill(dtbl);  //fill both tables with each query data
        sdata2.Fill(dtbl2);

        ds.Tables.Add(dtbl); //Add those tables to DataSet
        ds.Tables.Add(dtbl2);

        ds.Relations.Add("Your Relation Name",dtbl.Columns["id"], dtbl2.Columns["id_prov_comp"]);
        //or
        //ds.Relations.Add(ds.Tables["dtbl"].Columns["id"], ds.Tables["dtbl2"].Columns["id_prov_comp"]);

        ds.AcceptChanges();