Showing related Datatables via a Dataset in a Datagridview using collapsing/expanding rows .net

938 Views Asked by At

I have 2 datables being added to a dataset:

a parenttable:

Dim ctable As New DataTable("Category")
ctable.Columns.Add("Category", GetType(String))

a childtable:

Dim vtable As New DataTable("ValueTable")
vtable.Columns.Add("Category", GetType(String))
vtable.Columns.Add("Profile", GetType(String))
vtable.Columns.Add("Value", GetType(Double))

added to a dataset and linked via the column "category" using a datarelation:

Dim masterdata As New DataSet()
masterdata.Tables.Add(ctable)
masterdata.Tables.Add(vtable)
Dim dr As DataRelation = New DataRelation("ValueCategory",
                                              ctable.Columns("Category"),
                                              vtable.Columns("Category"), True)
masterdata.Relations.Add(dr)

adding this to a datagridview as datasource like:

aDataGridView.DataSource = masterdata.tables(0)

this will only show the parent table but I was hoping to have expandable rows related to my datarelation, but it wont work. I also tried binding my datasource to a bindingsource with the datasource as my masterdata table and my datamember being my relation, which would make more sense to me, but also this did not work. initially I followed the example below

https://www.mindstick.com/Articles/1416/expandable-and-collapsible-rows-in-datagrid-in-c-sharp-winforms

this is a similar question, but not the same:

Showing parent datatable in one datagridview and show child datatable elements in another?

1

There are 1 best solutions below

2
Oak_3260548 On

Indeed interesting question, never tried that and I thought I knew DataGridView well.

I would try to go around datarelation and do following:

  • define ctable and vtable with the same columns, because the datagridview has to have one set of columns
  • use column "Category" for the categories only, leave it empty for details (to distinguish the two types of rows
  • add hidden column IsExpanded as DataGridViewCheckBox. Default = false
  • create CellClick event, that will cycle for current row (e.rowindex) value in IsExpanded (but only if the row is a category row) and call an UpdateGrid() function
  • in UpgradeGrid() function take care adding details right into the (one) DataTable you are using as DataSource (aka join vtables into ctables for expanded categories; you can possibly get use of datarelation here).

I hope I explained my idea clearly. I will try it too when possible, this might come handy.