Display all child records of a parent in DataGridView

流过昼夜 提交于 2019-12-24 17:24:49

问题


I am new to .NET, and I don't really understand how it works. I have this project I have to do and I'm asked to display all parent records, and when I select a parent record there should be displayed all its children. So far I managed to display all the parent records, using a DataGridView.

private void display_btn_Click(object sender, EventArgs e)
        {
            dg.DataSource = data_set.Tables[0];
        }

The following code works but it displays all the records from the child. I know that I should compare somehow the primary key from the parent with the foreign key from the child and display from the child only those who are equal with the PK from the parent, but I don't know how to write it.

private void dg_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            dg2.DataSource = data_set.Tables[1];

        }

The code for creating the relation

 DataColumn parentColumn = data_set.Tables["Airline"].Columns["airline_id"];
                DataColumn childColumn = data_set.Tables["Plane"].Columns["airline_id"];

                rel_pln_air = new DataRelation("fk_pln_air", parentColumn, childColumn);
                data_set.Relations.Add(rel_pln_air);

The code for binding:

parentBindingSource.DataSource = data_set;
            parentBindingSource.DataMember = "Airline";
            childBindingSource.DataSource = parentBindingSource;
            childBindingSource.DataMember = "Plane";

回答1:


You must define mster-details relation between Tables[1] and Tables[2] in your dataset. Then you must set the DataSource of your child DataGridView to that relation.

Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls is the detailed explanation of your problem.

UPDATE

The airline_id can't be related to the plane_id. I thing you have the airline_id in you plane table to which you must reference.




回答2:


Link the same column as I stated in the comment
Use GetChildRows to walk the relationship

DataRow.GetChildRows



来源:https://stackoverflow.com/questions/22895665/display-all-child-records-of-a-parent-in-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!