This sample snippet shows how to use a data grid within a datagrid to display the master/detail relationship. Similar approach can be used to display DataGridView.
Place the following code in your ASP.NET page:
Now, bind data to the parent grid:
SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=StudentDatabase;Persist Security Info=True;User ID=userid;Password=pass"); SqlCommand command = new SqlCommand("SELECT StudentId, StudentName FROM Students", connection); connection.Open(); dgStudents.DataSource = command.ExecuteReader(); dgStudents.DataBind(); connection.Close();
The last thing to do is, on ItemDataBound event of the parent grid, bind the detail grid.
protected void dgStudents_ItemDataBound(object sender, DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=StudentDatabase;Persist Security Info=True;User ID=userid;Password=pass"); SqlCommand command;
int studentId = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "StudentId"));
DataGrid dgExamsResults = (DataGrid)e.Item.FindControl("dgExamsResults");
command = new SqlCommand("SELECT ExamDate, Marks FROM ExamResults WHERE StudentId = " + studentId, connection); connection.Open();
dgExamsResults.DataSource = command.ExecuteReader(); dgExamsResults.DataBind(); connection.Close(); } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|