Temporary Names
Temporary Names

Reputation: 21

How to display dataset in windows form?

My application takes any database as its input, it then detects the tables in that database and then fill all the tables into a DataSet. Now I have image of database in the dataset. Now my question is how to display this dataset into windows form.

DataSet is dynamic because everytime it will have n number of tables and each of these tables can have any number of rows and any number of columns.

Please read this question for context. compare databases (tables only) using C# and Ado.net

Upvotes: 1

Views: 5671

Answers (1)

Aimnox
Aimnox

Reputation: 899

The best way of displaying a table is with a DataGridView (DGV from now on). The thing is that the dgv is able to show one table, and only one.

So how do you do it? You need to have more than one DGV (one for each table of the dataset) or have some way of changing the table the DGV is showing.

Lets say you decide to have multiple DGV. I will not cover how to add them dinamically to the form, if you want to know ask for it and I will edit the answer.

You create one DGV for each table on the dataset:

List<DataGridView> DGVs = new List<DataGridView>();
foreach (DataTable DT in DS.Tables){
    DataGridView DGV = new DataGridView();
    DGV.DataSource=DT;
    DGVs.Add(DGV);
    //Add code for adding them to the form
}

Now you have one DataGridView for each table on the dataset.

If you prefer to have one DGV and be able to choose what table you want to show let me know


How to add controls dinamically

You need to decide how do you want to add them, in this case it will be one bellow the other.

For making them visible you need to:

  1. Add them to the father control
  2. Locate them
  3. Make them visible.

Adding to the father controls is a simple:

form1.Contols.Add(DGV)

Locating them is a bit more tricky, because you want each one of them in a diferent position, but relative to the previous one. To do this you need to create a Point and after that moving it X pixels down. so:

Point p = new Point(0,0); //Position of the first DGV, choose the one you want
p.Y += DGV.Height + 10; //Margin that you want

And then seting the DGV position to the point

DGV.Location = p;

And then just need to show the DGV

DGV.Show();

You can do it all in the for each loop, it will be something like:

List<DataGridView> DGVs = new List<DataGridView>();
Point p = new Point(0,0); //Position of the first DGV, choose the one you want
foreach (DataTable DT in DS.Tables){
    DataGridView DGV = new DataGridView();
    DGV.DataSource=DT;
    DGVs.Add(DGV);
    p.Y += DGV.Height + 10; //Margin that you want
    DGV.Location = p;
    this.Controls.Add(DGV);
    DGV.Show();
}

Note that if you dont need the list of DGV (It can be usefull in some cases) you can ignore the first and DGVs.Add(DGV); lines.

Upvotes: 2

Related Questions