C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Interview   Jobs   Projects   Offshore Development    
Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing | Talk to Us |



My Profile

Gifts

Active Members
TodayLast 7 Days more...







DataGrid within DataGrid - Master/Detail view


Posted Date: 11 Mar 2007    Resource Type: Code Snippets    Category: ADO.NET

Posted By: Tony John       Member Level: Gold
Rating:     Points: 10



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();
}
}





Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Using DefaultView to sort or filter a Table
Previous Resource: Create a DataTable, add rows and read records
Return to Discussion Resource Index
Post New Resource
Category: ADO.NET


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

internet fax

Contact Us    Privacy Policy    Terms Of Use